根据不同的列对数组进行排序

时间:2018-03-27 08:35:40

标签: php arrays multidimensional-array

我基于mysql表创建了一个数组

Array ( 
[0] => Array ( [id] => 1 [parent_ID] => 0  ) 
[1] => Array ( [id] => 2 [parent_ID] => 0  ) 
[2] => Array ( [id] => 3 [parent_ID] => 2  ) 
[3] => Array ( [id] => 4 [parent_ID] => 2  ) 
[4] => Array ( [id] => 5 [parent_ID] => 2  ) 
[5] => Array ( [id] => 6 [parent_ID] => 1  ) 
[6] => Array ( [id] => 7 [parent_ID] => 1  ) 
[7] => Array ( [id] => 8 [parent_ID] => 1  ) 
[8] => Array ( [id] => 9 [parent_ID] => 1  ) 

我想创建一个新数组,其中parent_ID的顺序基于ID。如果数组中的parent_ID为“1”,则需要将其直接放在ID为“1”的数组之后。新数组的输出必须如下:

Array ( 
[0] => Array ( [id] => 1 [parent_ID] => 0  ) 
[1] => Array ( [id] => 6 [parent_ID] => 1  ) 
[2] => Array ( [id] => 7 [parent_ID] => 1  ) 
[3] => Array ( [id] => 8 [parent_ID] => 1  ) 
[4] => Array ( [id] => 9 [parent_ID] => 1  ) 
[5] => Array ( [id] => 2 [parent_ID] => 0  ) 
[6] => Array ( [id] => 3 [parent_ID] => 2  ) 
[7] => Array ( [id] => 4 [parent_ID] => 2  ) 
[8] => Array ( [id] => 5 [parent_ID] => 2  ) 

我尝试使用usort函数对我的数组进行排序,但这只会对parent_ID或ID列进行排序。 PHP是否可以像示例一样对数组进行排序?

1 个答案:

答案 0 :(得分:0)

正如我对这个问题的评论所说,你提出的结果是虚假的......

但是这里有一些构造这种输出的简单算法:

<?php
$input = [
    ['id' => 1, 'parent_ID' => 0],
    ['id' => 2, 'parent_ID' => 0],
    ['id' => 3, 'parent_ID' => 2],
    ['id' => 4, 'parent_ID' => 2],
    ['id' => 5, 'parent_ID' => 2],
    ['id' => 6, 'parent_ID' => 1],
    ['id' => 7, 'parent_ID' => 1],
    ['id' => 8, 'parent_ID' => 1],
    ['id' => 9, 'parent_ID' => 1]
];
$data = [];
$output = [];

array_walk ($input, function($entry) use (&$data) {
    $data[$entry['parent_ID']][] = $entry;
});
array_walk ($data[0], function($entry) use ($data, &$output) {
    $output[] = $entry;
    foreach ($data[$entry['id']] as $child) {
        $output[] = $child;
    }
});
print_r($output);

执行的输出显然是:

Array
(
    [0] => Array
        (
            [id] => 1
            [parent_ID] => 0
        )

    [1] => Array
        (
            [id] => 6
            [parent_ID] => 1
        )

    [2] => Array
        (
            [id] => 7
            [parent_ID] => 1
        )

    [3] => Array
        (
            [id] => 8
            [parent_ID] => 1
        )

    [4] => Array
        (
            [id] => 9
            [parent_ID] => 1
        )

    [5] => Array
        (
            [id] => 2
            [parent_ID] => 0
        )

    [6] => Array
        (
            [id] => 3
            [parent_ID] => 2
        )

    [7] => Array
        (
            [id] => 4
            [parent_ID] => 2
        )

    [8] => Array
        (
            [id] => 5
            [parent_ID] => 2
        )

)

但是我想对你的情况做一些评论:

  • 你真的不应该为第一个元素存储0的值。他们没有父母,如果我的情况正确,那么该值实际上应该是null,而不是0
  • 您应该尝试在SQL查询中直接订购数据
  • 您应该重新考虑整体方法,因为显然您在使用给定数据模型对数据进行排序时存在巨大问题。这通常是应该重新设计的建模方法的标志。