按列升序排序php数组

时间:2016-11-11 10:11:27

标签: php arrays sorting multidimensional-array

  Array
(
    [content_type] => Array
        (
            [0] => story
            [1] => delhi
            [2] => tez
        )

    [type] => Array
        (
            [0] => video_id
            [1] => subcategory
            [2] => story_id
        )

    [fetch_id] => Array
        (
            [0] => 32
            [1] => 32
            [2] => 2
        )

    [order] => Array
        (
            [0] => 6
            [1] => 4
            [2] => 5
        )

    [label] => Array
        (
            [0] => dsfs fdsf dsf sdf 
            [1] => dfsdfs
            [2] => sdfsdfsd
        )

    [link] => Array
        (
            [0] => fsd fsdf sdf
            [1] => fsdfsdfdsf
            [2] => fsdfdsfds
        )

    [record] => Array
        (
            [0] => 10
            [1] => 8
            [2] => 12
        )

)

上面是我必须在order字段的基础上对这个数组进行排序的数组,它应该相应地缩短所有字段,如下例所示。

$arr['order'][0] = 4;
$arr['order'][1] = 5;
$arr['order'][2] = 6;

$arr['type'][0] = 'subcategory';
$arr['type'][1] = 'story_id';
$arr['type'][2] = 'video_id';

依旧.....

2 个答案:

答案 0 :(得分:0)

你可以试试这个 -

$new = array();
// Extract and get the keys as values
$order = array_flip($array['order']);
// sort them according to keys
ksort($order);
// loop through main array
foreach($array as $key => $sub_array) {
  // loop through order
  foreach ($order as $o) {
    // store the new value according to order
    $new[$key][] = $sub_array[$o];
  }
}

Demo

答案 1 :(得分:0)

一些较小的解决方案:

asort($array['order']);
foreach ($array as $key => $subArray) {
    $array[$key] = array_replace($array['order'], $subArray);
}

要重置键序列,您可以使用array_values()。