如何在php中将数组项放到最后? 我想把一些数组项放到最后一个位置,当我循环并输出$ arr到html时,这将使'other'项始终保持在最后。什么是最好和最简单的方法呢?
<?php
$arr=array(
'a'=>'hello',
'game'=>'boy',
'other'=>'good',
'name'=>'jimmy',
//...
);
// how to resort $arr to put other item to then end of $arr
$arr=array(
'a'=>'hello',
'game'=>'boy',
'name'=>'jimmy',
//...
'other'=>'good'
);
?>
答案 0 :(得分:2)
使用您给出的示例ksort($arr)
将按字母顺序对其进行排序,并将other
项放到最后。
第二个选项是使用other
从数组中删除array_slice
项,然后使用array_merge
将其放在后面
答案 1 :(得分:1)
假设您不是简单地要求根据键的字母属性对数组进行排序,给定您的数组:
$arr=array(
'a'=>'hello',
'game'=>'boy',
'other'=>'good',
'name'=>'jimmy',
);
您必须先取出旧密钥,同时保存其值:
$old = $arr['other'];
unset($arr['other']);
然后,将它附加到数组中:
$arr += array('other' => $old);
答案 2 :(得分:1)
首先存储您需要的所有元素。
喜欢
$arr=array(
'a'=>'hello',
'game'=>'boy',
'name'=>'jimmy');
之后添加
$arr['other']='good';
现在其他元素总是在最后......