如何通过顺序从多维数组中获取数组

时间:2013-03-07 10:55:18

标签: php arrays recursion multidimensional-array

我有这种阵列:

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"
  }
}
}

1 个答案:

答案 0 :(得分: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;
}