如何在 PHP 中将具有已知键的数组元素移动到数组的末尾? [英] How do I move an array element with a known key to the end of an array in PHP?

查看:37
本文介绍了如何在 PHP 中将具有已知键的数组元素移动到数组的末尾?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

脑子被一个相当微不足道的问题冻结了.如果我从这样的数组开始:

Having a brain freeze over a fairly trivial problem. If I start with an array like this:

$my_array = array(
                  'monkey'  => array(...),
                  'giraffe' => array(...),
                  'lion'    => array(...)
);

...并且新元素可能会使用不同的键添加,但始终是数组值.现在我可以确定第一个元素总是会有键 'monkey' 但我不能确定任何其他键.

...and new elements might get added with different keys but always an array value. Now I can be sure the first element is always going to have the key 'monkey' but I can't be sure of any of the other keys.

当我完成数组的填充后,我想将已知元素 'monkey' 移动到数组的末尾,而不会干扰其他元素的顺序.最有效的方法是什么?

When I've finished filling the array I want to move the known element 'monkey' to the end of the array without disturbing the order of the other elements. What is the most efficient way to do this?

我能想到的每一种方式似乎都有点笨拙,我觉得我错过了一些明显的东西.

Every way I can think of seems a bit clunky and I feel like I'm missing something obvious.

推荐答案

我能想到的唯一方法是删除它然后添加它:

The only way I can think to do this is to remove it then add it:

$v = $my_array['monkey'];
unset($my_array['monkey']);
$my_array['monkey'] = $v;

这篇关于如何在 PHP 中将具有已知键的数组元素移动到数组的末尾?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆