将具有特定键的数组元素移动到数组的开头

时间:2018-09-28 10:27:30

标签: php

我找不到关于此的任何东西,可能是我错过了,但是我想过滤/排序一个数组,该数组具有要移到顶部的键,因此它将是第一项。在我的示例中,我希望键3移到顶部。有没有简单的方法可以做到这一点?

// at default
[    
"key 1" : [ more data ],
"key 2" : [ even more data ],
"key 3" : [ some data ],// for this example I want this to be the first item
"key 4" : [ where is the data ]
]

// how i want it to be

move_to_first_in_array($array , 'key 3');

[  
"key 3" : [ some data ],// for this example I want this to be the first item  
"key 1" : [ more data ],
"key 2" : [ even more data ],
"key 4" : [ where is the data ]
]

3 个答案:

答案 0 :(得分:4)

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

这使用+运算符返回两个数组的并集,其中左侧操作数中的元素优先。 From the documentation

  

+运算符返回添加到左侧数组的右侧数组;对于两个数组中都存在的键,将使用左侧数组中的元素,而右侧数组中的匹配元素将被忽略。

请参见https://3v4l.org/ZQV2i

答案 1 :(得分:0)

怎么样:

function move_to_first_in_array(&$array, $key)
{
    $element = $array[$key];
    unset($array[$key]);
    $array = [$key => $element] + $array;
}

这真的很丑,但是可​​以。

答案 2 :(得分:0)

也可以尝试以这种方式来构建核心PHP。

<?php

$array = array(    
"key 1" => " more data ",
"key 2" => "even more data",
"key 3" => "some data ",// for this example I want this to be the first item
"key 4" => "where is the data"
);
echo "<pre>";print_r($array);
echo "<br>";


$array2 = array("key 3","key 1","key 2","key 4");

$orderedArray = array();
foreach ($array2 as $key) {
    $orderedArray[$key] = $array[$key];
}

echo "<pre>";print_r($orderedArray);exit;

?>

答案:

Array
(
    [key 1] =>  more data 
    [key 2] => even more data
    [key 3] => some data 
    [key 4] => where is the data
)

Array
(
    [key 3] => some data 
    [key 1] =>  more data 
    [key 2] => even more data
    [key 4] => where is the data
)