简体   繁体   English

PHP通过键取消关联数组

[英]PHP unshift associative array by the key

Im trying to move an array item to the top of the array using unshift but I get an unexpected result: 我试图使用unshift将数组项移动到数组的顶部,但是得到了意外的结果:

$all_people = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
   $new_value = $all_people['Ben'];
   array_unshift($all_people, $new_value);

Here I expect to have an array where "Ben"=>"37 is the first item but I end up with this: 在这里,我希望有一个数组,其中"Ben"=>"37是第一项,但最终得到的是:

array(4) { [0]=> int(0) [1]=> string(5) "Peter" [2]=> string(3) "Ben" [3]=> string(3) "Joe" }

The first element is empty and "Ben" has not moved to the top which I thought was going to happen. 第一个元素为空,“ Ben”没有移到我认为将要发生的顶部。 Can someone help me out? 有人可以帮我吗? Thanks! 谢谢!

Try php array union operator for this: 尝试使用php 数组联合运算符

$all_people = array('Ben' => $all_people['Ben']) + $all_people;

The first value in the union will always be first and duplicate keys will be automatically unset. 联合中的第一个值始终是第一个,重复键将自动取消设置。 So this takes care of everything in one shot. 这样一来便可以处理所有事情。

You could also make this in to a function if it's something you need frequently in your application: 如果您的应用程序中经常需要它,您也可以将其添加到函数中:

function moveToTop($array, $key) {
    return array($key => $array[$key]) + $array;
}

$all_people = moveToTop($all_people,'Ben');

Here is the way to move any element to the first. 这是将任何元素移到第一个元素的方法。

$all_people = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
$ben["Ben"] = $all_people["Ben"];
$all_people = $ben + $all_people;

Live Demo 现场演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM