本文介绍了使用另一个数组作为输入对数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想使用下面提供的另一个数组对以下数组进行排序。
I would like to sort the following array using another array provided bellow.
例如。我有以下数组:
[note] => Array
(
[0] => 'note1'
[1] => 'note2'
[2] => 'note3'
),
[text] => Array
(
[0] => 'text1'
[2] => 'test3'
),
[year] => Array
(
[0] => '2002'
[1] => '2000'
[2] => '2011'
)
我有数组:
$sortBy = array('2011', '2000', '2002').
我想根据$ sortBy数组的值对上述数组进行排序。
I would like to sort the above array according the values of $sortBy array.
期望的结果是:
[note] => Array
(
[0] => 'note3'
[1] => 'note2'
[2] => 'note1'
),
[text] => Array
(
[0] => 'test3'
[2] => 'text1'
),
[year] => Array
(
[0] => '2011'
[1] => '2000'
[2] => '2002'
)
推荐答案
您有一个数组:
$array = array(
'note' => array('note1', 'note2', 'note3'),
'text' => array('text1', 'text2', 'text3'),
'year' => array('2002', '2000', '2011')
);
事物的顺序:
$sortBy = array('2011', '2000', '2002');
$sortOrder = $array['year'];
然后,您将了解如何对年份进行排序:
You then find out how the year needs to be sorted:
array_walk($sortOrder, function(&$v) use ($sortBy) {$v = array_search($v, $sortBy);});
然后根据该顺序对整个数组进行排序:
To then sort the whole array based on that order:
array_multisort($sortOrder, $array['note'], $array['text'], $array['year']);
完整示例:
$array = array(
'note' => array('note1', 'note2', 'note3'),
'text' => array('text1', 'text2', 'text3'),
'year' => array('2002', '2000', '2011')
);
$sortBy = array('2011', '2000', '2002');
$sortOrder = $array['year'];
array_walk($sortOrder, function(&$v) use ($sortBy) {$v = array_search($v, $sortBy);});
array_multisort($sortOrder, $array['note'], $array['text'], $array['year']);
Output / :
Output/Demo:
Array(
[note] => Array(
[0] => note3
[1] => note2
[2] => note1
)
[text] => Array(
[0] => text3
[1] => text2
[2] => text1
)
[year] => Array(
[0] => 2011
[1] => 2000
[2] => 2002
)
)
编辑:映射的变体保留了 array_search
:
$sortBy = array_flip(array('2011', '2000', '2002'));
$sortOrder = $array['year'];
array_walk($sortOrder, function(&$v) use ($sortBy) {$v = $sortBy[$v];});
array_multisort($sortOrder, $array['note'], $array['text'], $array['year']);
Edit2: PHP 5.2封装为一个函数,完全参数化: / p>
PHP 5.2 wrapped into a single function, full parametrization:
/**
* @param array $array
* @param string|int $by key/offset
* @param array $order
* @return array
*/
function array_multisort_by_order(array $array, $by, array $order)
{
$order = array_flip($order);
$params[] = $array[$by];
foreach($params[0] as &$v) $v = $order[$v];
foreach($array as &$v) $params[] = &$v; unset($v);
call_user_func_array('array_multisort', $params);
return $array;
}
// Usage:
array_multisort_by_order($array, 'year', array('2011', '2000', '2002'));
这篇关于使用另一个数组作为输入对数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!