最佳方式按键显示数组顺序

最佳方式按键显示数组顺序

问题描述:

<?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/>';
}
?>

the out put of this code is

1:-Hi
4:-are
3:-How
7:-my
6:-you
9:-brother

but i need to display this order by key. please tell me which is easiest way

thanks

 &lt;?php 
 $ array = array(
“1”=&gt;'嗨 ',
“4”=&gt;'是',
“3”=&gt;'如何',
“7”=&gt;'我',
“6”=&gt;'你',  
“9”=&gt;'兄弟',
); 
 
forEach($ array as $ key =&gt; $ value){
 echo $ key; 
 echo': - '; 
 print_r  ($ value); 
 echo'&lt; br /&gt;'; 
} 
?&gt; 
  code>  pre> 
 
 

此代码的输出为

  1:嗨\ N4:-are \ N3: - 如何\ N7:-My \ N6:-you \ N9:-brother 
 代码>   pre> 
 
 

但我需要按键显示此顺序。 请告诉我哪种方式最简单 p>

谢谢 p> div>

Use ksort

ksort($array);

foreach($array as $key => $value) {
    echo $key;
    echo ':-';
    print_r($value);
    echo '<br/>';
}

The nice thing about PHP is that there's a function for everything. You can use the ksort function to sort the array by its keys: http://php.net/manual/en/function.ksort.php

Your new code would look like this:

<?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/>';
}
?>

use ksort(), this will arrange it by key order.

<?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/>';
}
?>