<?php
$array = array(
"1" => 'Hi',
"4" => 'are',
"3" => 'How',
"7" => 'my',
"6" => 'you',
"9" => 'brother',
);
forEach($array as $key => $value) {
echo $key;
echo ':-';
print_r($value);
echo '<br/>';
}
?>
此代码的输出是
1:-Hi
4:-are
3:-How
7:-my
6:-you
9:-brother
但我需要按键显示此顺序。请告诉我哪种方式最简单
感谢
答案 0 :(得分:3)
使用ksort
ksort($array);
foreach($array as $key => $value) {
echo $key;
echo ':-';
print_r($value);
echo '<br/>';
}
答案 1 :(得分:2)
关于PHP的好处是,它有一个功能。您可以使用ksort
函数按键对其进行排序:http://php.net/manual/en/function.ksort.php
您的新代码如下所示:
<?php
$array = array(
"1" => 'Hi',
"4" => 'are',
"3" => 'How',
"7" => 'my',
"6" => 'you',
"9" => 'brother',
);
ksort($array);
forEach($array as $key => $value) {
echo $key;
echo ':-';
print_r($value);
echo '<br/>';
}
?>
答案 2 :(得分:0)
使用ksort()
,这将按键顺序排列。
<?php
$array = array(
"1" => 'Hi',
"4" => 'are',
"3" => 'How',
"7" => 'my',
"6" => 'you',
"9" => 'brother',
);
ksort($array);
forEach($array as $key => $value) {
echo $key;
echo ':-';
print_r($value);
echo '<br/>';
}
?>