简体   繁体   English

如何通过一个子阵列值对数组子阵列进行排序? (PHP)

[英]How can i sort array subarrays by one subarray values? (PHP)

I have an array like this: 我有这样一个数组:

array(
    'sortBy' => array(0 => 3,   1 => 2,   2 => 1),
    'other'  => array(0 => 'x', 1 => 'y', 2 => 'z'),
    'xxx'    => array(0 => 3,   1 => 2,   2 => 1),
    ...
)

How can I sort contents of subarray other by values in sortBy ? 如何通过sortBy中的值对其他子阵列的内容进行排序? There's unlimited amount of other subarrays inside that one array, but the keys inside these subarrays are always same(eg in sortBy , other , xxx the values of key 0 must all be sorted together) 在一个数组中有无限量的其他子数组,但这些子数组中的键总是相同的(例如在sortBy中其他xxx ,键0的值必须全部排序在一起)

Sorted array would look like this: 排序数组看起来像这样:

array(
    'sortBy' => array(0 => 1,   1 => 2,   2 => 3),
    'other'  => array(0 => 'z', 1 => 'y', 2 => 'x'),
    'xxx'    => array(0 => 1,   1 => 2,   3 => 3)
)

You could use array_multisort() to good effect. 你可以使用array_multisort()来达到良好的效果。

$array = array(
    'sortBy' => array(3,   2,   1),
    'other'  => array('x', 'y', 'z'),
    'xxx'    => array(3,   2,   1),
);

array_multisort($array['sortBy'], SORT_NUMERIC, $array['other'], $array['xxx']);

var_export($array);

The above example prints the following: 上面的示例打印以下内容:

array (
  'sortBy' => 
  array (
    0 => 1,
    1 => 2,
    2 => 3,
  ),
  'other' => 
  array (
    0 => 'z',
    1 => 'y',
    2 => 'x',
  ),
  'xxx' => 
  array (
    0 => 1,
    1 => 2,
    2 => 3,
  ),
)

Edit 编辑

Since you decided the array's keys could be anything (other than the one definite key: sortBy ), then array_multisort() can still be used albeit called with a more dynamic list of arguments. 既然你确定数组的键可以是任何东西(除了一个明确的键: sortBy ),那么尽管使用更动态的参数列表调用,仍然可以使用array_multisort()

$array = array( … );

$args = array(&$array['sortBy'], SORT_NUMERIC);
foreach ($array as $key => $value) {
    if ($key !== 'sortBy') {
        $args[] = &$array[$key];
    }
}
call_user_func_array('array_multisort', $args);
unset($args);

var_export($array);

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

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