Sorting array for every child coming after parent

后端 未结 2 1262
挽巷
挽巷 2021-01-07 08:08

I have an array like that:

 1,
        \'parent_id\' => null
    ),
    array(
        \'id\' => 2,
             


        
2条回答
  •  不知归路
    2021-01-07 08:26

    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);.

提交回复
热议问题