0

我有这种数组:

array(2) {
[1] => array(3) {
  [3] => array(3) {
    ["data"] => array(3) {
      ["id"] => string(1) "3"
      ["depth"] => string(1) "1"
      ["parent_id"] => NULL
    }
  }
  [4] => array(3) {
    ["data"] => array(3) {
      ["id"] => string(1) "4"
      ["depth"] => string(1) "1"
      ["parent_id"] => NULL
    }
  }
  [2] => array(3) {
    ["data"] => array(3) {
      ["id"] => string(1) "2"
      ["depth"] => string(1) "1"
      ["parent_id"] => NULL
    }
  }
}
[2] => &array(3) {
  [15] => array(3) {
    ["data"] => array(3) {
      ["id"] => string(2) "15"
      ["depth"] => string(1) "2"
      ["parent_id"] => string(1) "3"
    }
  }
  [16] => array(3) {
    ["data"] => array(3) {
      ["id"] => string(2) "16"
      ["depth"] => string(1) "2"
      ["parent_id"] => string(1) "2"
    }
  }
  [18] => array(3) {
    ["data"] => array(3) {
      ["id"] => string(2) "18"
      ["depth"] => string(1) "2"
      ["parent_id"] => string(1) "4"
    }
  }
}
}

第一级意味着深度(1 没有孩子,2 有父母没有孩子,等等)。数组项的顺序是正确的。我需要以相同的顺序获取不同的数组(当然取决于级别)。

array(6) {
[3] => array(3) {
  ["data"] => array(3) {
    ["id"] => string(1) "3"
    ["depth"] => string(1) "1"
    ["parent_id"] => NULL
  }
}
[15] => array(3) {
  ["data"] => array(3) {
    ["id"] => string(1) "15"
    ["depth"] => string(1) "1"
    ["parent_id"] => 3
  }
}
[4] => array(3) {
  ["data"] => array(3) {
    ["id"] => string(1) "4"
    ["depth"] => string(1) "1"
    ["parent_id"] => NULL
  }
}
[18] => &array(3) {
  ["data"] => array(3) {
    ["id"] => string(2) "18"
    ["depth"] => string(1) "2"
    ["parent_id"] => string(1) "4"
  }
}
[2] => array(3) {
  ["data"] => array(3) {
    ["id"] => string(2) "2"
    ["depth"] => string(1) "2"
    ["parent_id"] => NULL
  }
}
[16] => array(3) {
  ["data"] => array(3) {
    ["id"] => string(2) "16"
    ["depth"] => string(1) "2"
    ["parent_id"] => string(1) "2"
  }
}
}
4

1 回答 1

0

**

第一个解决方案

**

我找到了解决方案,但我不知道如何从中进行递归。它仅适用于两个级别。第三级是糟糕的秩序。变量 $this->hierarchicalData 包含第一个数组。

$_sortedHierarchyData = array();
foreach ($this->hierarchicalData as $levelKey => $_level) {
  foreach ($_level as $itemKey => $item) {
    if (isset($this->hierarchicalData[$levelKey + 1])) {
      $_sortedHierarchyData[$item['data']['id']] = $item;
      $children = $this->searchChildrenFromLevelOfHieararchicalSortedData($item['data']['id'], $this->hierarchicalData[$levelKey + 1]);
      $_sortedHierarchyData += $children;
    }               
  }
}

function searchChildrenFromLevelOfHieararchicalSortedData($parent_id, $level)
{
  $_children = array();
  foreach ($level as $key => $item) {
    if ($item['data']['parent_id'] === $parent_id) {
      $_children[$key] = $item;
    }
  }
  return $_children;
}
于 2013-03-07T13:34:30.063 回答