到目前为止,我所有的研究表明,如果不编写冗长的函数(例如这里的解决方案),就无法实现这一点
当然,使用预定义的PHP函数有一种更简单的方法来实现这一点吗?
为了清楚起见,我正在尝试执行以下操作:
$test = array(
'bla' => 123,
'bla2' => 1234,
'bla3' => 12345
);
// Call some cool function here and return the array where the
// the element with key 'bla2' has been shifted to the beginning like so
print_r($test);
// Prints bla2=1234, bla=>123 etc...
我已经考虑使用以下函数,但到目前为止还无法自己编写解决方案。
- array_unshift
- array_merge
总结一下
我想:
- 将元素移动到数组的开头
- 。同时维护关联数组键
这
对我来说似乎很有趣。但在这里你去:
$test = array(
'bla' => 123,
'bla2' => 1234,
'bla3' => 12345
);
//store value of key we want to move
$tmp = $test['bla2'];
//now remove this from the original array
unset($test['bla2']);
//then create a new array with the requested index at the beginning
$new = array_merge(array('bla2' => $tmp), $test);
print_r($new);
输出如下所示:
Array
(
[bla2] => 1234
[bla] => 123
[bla3] => 12345
)
你可以把它变成一个简单的函数,它接受一个键和一个数组,然后输出新排序的数组。
更新
我不确定为什么我没有默认使用 uksort
,但你可以做得更干净一点:
$test = array(
'bla' => 123,
'bla2' => 1234,
'bla3' => 12345
);
//create a function to handle sorting by keys
function sortStuff($a, $b) {
if ($a === 'bla2') {
return -1;
}
return 1;
}
//sort by keys using user-defined function
uksort($test, 'sortStuff');
print_r($test);
这将返回与上述代码相同的输出。
这不是严格意义上的 Ben 问题的答案(这很糟糕吗?) - 但这经过优化,可以将项目列表放在列表的顶部。
/**
* Moves any values that exist in the crumb array to the top of values
* @param $values array of options with id as key
* @param $crumbs array of crumbs with id as key
* @return array
* @fixme - need to move to crumb Class
*/
public static function crumbsToTop($values, $crumbs) {
$top = array();
foreach ($crumbs AS $key => $crumb) {
if (isset($values[$key])) {
$top[$key] = $values[$key];
unset($values[$key]);
}
}
return $top + $values;
}