根据排序普通数组的顺序多维数组 [英] Sorting multidimensional array based on the order of plain array
本文介绍了根据排序普通数组的顺序多维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这样的数组:
$ =航线阵列(
阵列(
code'=> PZSA',
'名'=> 广场圣安东尼奥,
)
阵列(
code'=> AVAD',
'名'=> AV阿斯图里亚斯,
)
阵列(
code'=> AVAR',
'名'=> AV西蒙涅托',
)
);
和我想基于下一个按键对它进行排序:
$ TARGET =阵列('AVAD','AVAR','PZSA');
因此,排序后的数组将是:
阵列
(
[0] =>排列
(
[code => AVAD
[名] => AV阿斯图里亚斯
)[1] =>排列
(
[code => AVAR
[名] => AV西蒙·涅托
)[2] =>排列
(
[code => PZSA
[名] =>广场圣安东尼奥
))
我已经试过这和它的作品,但我觉得实在是太多了code这个简单的事情。任何替代方案?谢谢你。
函数_sort($数组$ orderArray){
$下令=阵列();
的foreach($ orderArray为$键){
$下令[] =查找($键,$阵列);
}
返回$有序;
} 功能查找($code,$路由){
的foreach($路线为$关键=> $值){
如果($路线[$关键] ['code'] == $code){
返回路线$ [$关键];
}
}
}$排序= _sort($路径,$目标);
解决方案
$ target_flip = array_flip($目标);usort($路线,功能($ A,$ B)使用($ target_flip){
返回($ target_flip [$一个['code']]< $ target_flip [$ B ['code'])? -1:1;
});
演示:
文件:
- http://php.net/manual/en/function.array- flip.php
- http://php.net/manual/en/function.usort.php
- http://php.net/manual/en/functions.anonymous.php
I have this array:
$routes = array(
array(
'code' => 'PZSA',
'name' => 'PLaza san antonio',
),
array(
'code' => 'AVAD',
'name' => 'Av de asturias',
),
array(
'code' => 'AVAR',
'name' => 'Av simon nieto',
)
);
And I want to sort it based on the next keys:
$target = array('AVAD', 'AVAR', 'PZSA');
So the sorted array will be:
Array
(
[0] => Array
(
[code] => AVAD
[name] => Av de asturias
)
[1] => Array
(
[code] => AVAR
[name] => Av simon nieto
)
[2] => Array
(
[code] => PZSA
[name] => PLaza san antonio
)
)
I've tried this and it works, but I think is too much code for this simple thing. Any alternatives? Thanks.
function _sort($array, $orderArray) {
$ordered = array();
foreach ($orderArray as $key) {
$ordered[] = find($key, $array);
}
return $ordered;
}
function find($code, $routes) {
foreach ($routes as $key => $value) {
if ($routes[$key]['code'] == $code) {
return $routes[$key];
}
}
}
$sorted = _sort($routes, $target);
解决方案
$target_flip = array_flip($target);
usort($routes, function($a, $b) use ($target_flip){
return ($target_flip[$a['code']] < $target_flip[$b['code']]) ? -1 : 1;
});
Demo:
Docs:
- http://php.net/manual/en/function.array-flip.php
- http://php.net/manual/en/function.usort.php
- http://php.net/manual/en/functions.anonymous.php
这篇关于根据排序普通数组的顺序多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文