对PHP数组进行排序,得到混合结果


Sort a PHP array bringing back mixed results

如何按字母顺序排序这个数组?我使用以下代码

打印这个数组

<?php print_r($artists); ?>

我想做一些

<?php ksort($artists); ?><?php asort($artists); ?>

在我打印出$artists之前可以工作,但是它带来了混合的结果。

Array ( [0] =>
Bloor, Simon
[1] =>
Bloor, Tom
[2] =>
Burt, Theo
[3] =>
Berendes, Eva
[4] =>
Barnes, Kristian
[5] =>
Bajo, Elena
)

谢谢,如果你需要更多的信息,请不要犹豫问我。R

添加了一个完整的代码片段:http://snippi.com/s/14ox0cx

我在sort($artists)之前和之后添加了var_dump($artists),并在这里显示了一个before/after输出的示例。

<h1>Before</h1>
<?php var_dump($artists); ?>
<?php sort($artists); ?>
<h1>After</h1>
<?php var_dump($artists); ?>
Before
array(6) { [0]=> string(97) "
Bloor, Simon
" [1]=> string(95) "
Bloor, Tom
" [2]=> string(95) "
Burt, Theo
" [3]=> string(140) "
Berendes, Eva
" [4]=> string(107) "
Barnes, Kristian
" [5]=> string(99) "
Bajo, Elena
" }
After
array(6) { [0]=> string(140) "
Berendes, Eva
" [1]=> string(97) "
Bloor, Simon
" [2]=> string(95) "
Bloor, Tom
" [3]=> string(95) "
Burt, Theo
" [4]=> string(107) "
Barnes, Kristian
" [5]=> string(99) "
Bajo, Elena
" }

ksort()不是你想要的;它按键排序,数组保持原样。
sort():如果"失败",你只是一个疯狂的猜测:你正在使用一个for($i=0; $i<count($arr);...循环来迭代数组?这使得输出保持原样,因为sort()保留了数组键。

尝试简单的sort()或natsort()和foreach循环。

<?php
$arr = array (
    'Bloor, Simon',
    'Bloor, Tom',
    'Burt, Theo',
    'Berendes, Eva',
    'Barnes, Kristian',
    'Bajo, Elena'
);
natsort($arr);
foreach($arr as $e) {
    echo $e, "'r'n";
}

ksort():按键对数组进行排序,如果您想按字母顺序对数组进行排序,则此处无效。

ksort():对数组进行排序并维护索引关联

可以使用sort():简单地对数组进行排序!

<?php
$artists = array ("Bloor, Simon", "Bloor, Tom", "Burt, Theo", "Berendes, Eva", "Barnes, Krist", "Bajo, Elena");
print_r($artists);
$artists = array ("Bloor, Simon", "Bloor, Tom", "Burt, Theo", "Berendes, Eva", "Barnes, Krist", "Bajo, Elena");
ksort($artists);
print_r($artists);
$artists = array ("Bloor, Simon", "Bloor, Tom", "Burt, Theo", "Berendes, Eva", "Barnes, Krist", "Bajo, Elena");
asort($artists);
print_r($artists);
$artists = array ("Bloor, Simon", "Bloor, Tom", "Burt, Theo", "Berendes, Eva", "Barnes, Krist", "Bajo, Elena");
sort($artists);
print_r($artists);
?>

简单演示

正如在评论中提到的,排序是有效的。

$artists = array ( 
 'Bloor, Simon', 
 'Bloor, Tom', 
 'Burt, Theo', 
 'Berendes, Eva', 
 'Barnes, Kristian', 
 'Bajo, Elena');
sort($artists);
print_r($artists);

查看此处的代码证明