根据父ID值将PHP数组从一维转换为多维

时间:2018-10-06 02:57:53

标签: php arrays laravel

我有一个代表多维数据的一维对象数组:

array(
    array(
        "id" => 1,
        "parent_id" => 0,
        "content" => 'des'
    ),
    array(
        "id" => 2,
        "parent_id" => 3,
        "content" => 'abc'
    ),
    array(
        "id" => 3,
        "parent_id" => 1,
        "content" => 'jjjj'
    ),
    array(
        "id" => 4,
        "parent_id" => 5,
        "content" => 'dsfsd'
    ),
    array(
        "id" => 5,
        "parent_id" => 0,
        "content" => 'dsfsd'
    )
);

如何将其转换为多维数组?

array(
    array(
        "id" => 1,
        "parent_id" => 0,
        "content" => 'des'
    ),
    array(
        "id" => 3,
        "parent_id" => 1,
        "content" => 'jjjj'
    ),
    array(
        "id" => 2,
        "parent_id" => 3,
        "content" => 'abc'
    ),
    array(
        "id" => 5,
        "parent_id" => 0,
        "content" => 'dsfsd'
    ),
    array(
        "id" => 4,
        "parent_id" => 5,
        "content" => 'dsfsd'
    )
);

我想按父级后面的id和子级排序,如果parent_id = 0,则它是根元素。非常感谢大家!

2 个答案:

答案 0 :(得分:2)

我认为您需要按parent_id对数组进行排序。

array_sort()是laravel辅助函数:https://laravel.com/docs/5.7/helpers#method-array-sort

$sorted = array_sort($array, 'parent_id');

输出

array:5 [▼
  0 => array:3 [▼
    "id" => 1
    "parent_id" => 0
    "content" => "des"
  ]
  4 => array:3 [▼
    "id" => 5
    "parent_id" => 0
    "content" => "dsfsd"
  ]
  2 => array:3 [▼
    "id" => 3
    "parent_id" => 1
    "content" => "jjjj"
  ]
  1 => array:3 [▼
    "id" => 2
    "parent_id" => 3
    "content" => "abc"
  ]
  3 => array:3 [▼
    "id" => 4
    "parent_id" => 5
    "content" => "dsfsd"
  ]
]

答案 1 :(得分:0)

这是我的代码(完成)

function sort($array){
    $newArray = [];
    sortLoop($array, $newArray);
    return $newArray;
}
function sortLoop($array, &$newArray, $parent_id = 0){
    foreach ($array as $key => $item) {
        if ($item['parent_id'] == $parent_id) {
            $newArray[] = $item;
            unset($array[$key]);
            sortLoop($array,$newArray, $item['id']);
        }
    }
}

希望这对某人有用。