如何在PHP中将数组项放到末尾?

3

如何将PHP数组项放到最后一个位置?
我想把数组的某些元素放在最后一个位置,当我循环并将$ arr输出到html时,这将保持“其他”项目始终在最后。有什么最好且简单的方法来做到这一点吗?

<?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'
);
?>
3个回答

2

根据您提供的示例,ksort($arr)会按字母顺序对数组进行排序,并将other项放在最后。

第二个选项是使用array_slice从数组中删除other项,然后使用array_merge将其放置在末尾。


array_slice() 无法根据键值进行搜索。 - Ja͢ck

1
假设您不仅仅是要按键的字母顺序对数组进行排序,考虑到您的数组:
$arr=array(
    'a'=>'hello',
    'game'=>'boy',
    'other'=>'good',
    'name'=>'jimmy',
);

您需要先取出旧的密钥,同时保存其值:

$old = $arr['other'];
unset($arr['other']);

然后,像这样将其附加到数组中:
$arr += array('other' => $old);

1

首先存储您所需的所有元素。

例如

$arr=array( 'a'=>'你好', 'game'=>'男孩', 'name'=>'吉米');

之后添加

$arr['other']='good';

现在其他元素总是在最后.....

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接