Sorting array for every child coming after parent

两盒软妹~` 提交于 2019-12-09 01:50:42

问题


I have an array like that:

<?php
array(
    array(
        'id' => 1,
        'parent_id' => null
    ),
    array(
        'id' => 2,
        'parent_id' => 1
    ),
    array(
        'id' => 3,
        'parent_id' => null
    ),
    array(
        'id' => 4,
        'parent_id' => 2
    )
)

I need to sort it to every child comes after it's immediate parent. So, ID 4 item should come right after ID 2.

Thanks.


回答1:


Working solution : PHP has user define sorting function uasort I have used this to sort your array.

<?php
$data = array(
    array(
        'id' => 1,
        'parent_id' => null
    ),
    array(
        'id' => 2,
        'parent_id' => 1
    ),
    array(
        'id' => 3,
        'parent_id' => null
    ),
    array(
        'id' => 4,
        'parent_id' => 2
    )
);



function cmp($a, $b) {    
    if ($a['parent_id'] == $b['parent_id']) {
        return 0;
    }
    return ($a['parent_id'] < $b['parent_id']) ? -1 : 1;
}

uasort($data, 'cmp');
echo '<pre>';
print_r($data);
echo '</pre>';



回答2:


This working solution works with array_multisort().

Try with:

$data = array(
    array(
        'id' => 1,
        'parent_id' => null
    ),
    array(
        'id' => 2,
        'parent_id' => 1
    ),
    array(
        'id' => 3,
        'parent_id' => null
    ),
    array(
        'id' => 4,
        'parent_id' => 2
    )
);

$parent_ids = array();
foreach ($data as $item) {
    $parent_ids[]  = $item['parent_id'];
}

array_multisort($parent_ids, SORT_ASC, $data);

If you want null values to be at the end replace that foreach with:

foreach ($data as $item) {
    if (is_null($item['parent_id'])) {
        $item['parent_id'] = PHP_INT_SIZE;
    }
    $parent_ids[]  = $item['parent_id'];
}

See result with: print_r($data);.



来源:https://stackoverflow.com/questions/13661298/sorting-array-for-every-child-coming-after-parent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!