带有对象的数组作为子对象添加到新数组

Array with Objects add to new Array as Child

我现在觉得自己很愚蠢,无法理解它

我得到了一个包含 stdClass 对象的数组,我想对它们进行新排序或用它构建另一个数组

Array
(
    [0] => stdClass Object
        (
            [id] => 15
            [top_id] => 13
            [title] => Menu 6
            [online] => 1
            [displayOrder] => 15
        )

    [1] => stdClass Object
        (
            [id] => 14
            [top_id] => 13
            [title] => Menu 5
            [online] => 0
            [displayOrder] => 14
        )

    [2] => stdClass Object
        (
            [id] => 13
            [top_id] => 0
            [title] => Menu 4
            [online] => 0
            [displayOrder] => 13

        )

    [3] => stdClass Object
        (
            [id] => 12
            [top_id] => 11
            [title] => Menu 3
            [online] => 1
            [displayOrder] => 12
        )

)

我想要的数组是这样的

(
    [2] => stdClass Object
        (
            [id] => 13
            [top_id] => 0
            [title] => Menu 4
            [online] => 0
            [displayOrder] => 13
            [children] =>
            (
               [id] => 11
               [top_id] => 13
               [title] => Menu 2
               [online] => 0
               [displayOrder] => 11
               [children] =>
                (
                    [id] => 12
                    [top_id] => 11
                    [title] => Menu 3
                    [online] => 1
                    [displayOrder] => 12
                )
)

我今天尝试了很多我在网上找到的东西,但我无法找到正确的答案/或让它工作

请告诉我正确方向的人,并简要解释为什么是这样?

谢谢你和最诚挚的问候

我对 php 不太熟悉,但我可以用 JS

解决这个问题

function doOrderSort(a, b) {
  return parseInt(a.displayOrder) - parseInt(b.displayOrder);
}

function findAndAppendSubs(item, originItems) {
  var allItems = Object.assign([], originItems);
  var subItems = allItems.filter(inner => inner.top_id === item.id);


  if (subItems !== undefined && subItems.length > 0) {
    for (var i = 0; i < subItems.length; i++) {
      subItems[i] = findAndAppendSubs(subItems[i], allItems)
    }
    item.subItems = subItems.sort(doOrderSort);
  }
  return item;

}


function sortAndAppendAllSubs(itemList) {

  var allItems = Object.assign([], itemList);
  var topItems = allItems.filter(inner => parseInt(inner.top_id) === 0);
  var resultList = [];
  if (topItems !== undefined && topItems.length > 0) {
    for (var it = 0; it < topItems.length; it++) {
      resultList.push(findAndAppendSubs(topItems[it], allItems));
    }
  }
  return resultList.sort(doOrderSort);
}

https://jsfiddle.net/3b4s79L5/ (打开控制台查看结果:)

编辑:添加排序功能并忽略字符串或数字作为 top_id