0

我有以下数组,我拥有的唯一值是子页面的 ID(在本例中为 35)。我希望收到父母,所以当有更多孩子时我可以遍历所有孩子(在这种情况下我正在寻找数字 34)。

[34] => Array
    (
        [id] => 34
        [label] => Over Ons
        [type] => page
        [url] => 8
        [children] => Array
            (
                [0] => Array
                    (
                        [id] => 35
                        [label] => Algemeen
                        [type] => page
                        [url] => 9
                    )

            )

    )

有没有人对此有很好的解决方案?

提前致谢。

4

3 回答 3

0

When you build the Array (assuming you are creating it on your own), add a reference to the parent:

<?php

$parent = array("id" => 1, "parent" => null);
$child = array("id" => 2, "parent" => &$parent); //store reference
$child2 = array("id" => 3, "parent" => &$parent); //store reference
$parent["childs"][] = $child;
$parent["childs"][] = $child2;

foreach ($parent["childs"] AS $child){
    echo $child["id"]." has parent ".$child["parent"]["id"]. "<br />";
}

//2 has parent 1
//3 has parent 1
?>

This allows you to walk the array "very smooth", using childs and parent entries. (Basically its a tree, then)

于 2013-07-23T10:26:35.000 回答
0

尝试:

foreach ($arr as $key => $value) {
    foreach ($value["children"] as $child) {
        if ($child["id"] == $you_look_for) return $key; // or $value["id"] ?
    }
}

但是,这将仅返回包含具有 id 的孩子的数组的第一个 id $you_look_for

于 2013-07-23T10:20:15.607 回答
0

尝试:

$input    = array( /* your data */ );
$parentId = 0;
$childId  = 35;

foreach ( $input as $id => $parent ) {
  foreach ( $parent['children'] as $child ) {
    if ( $child['id'] == $childId ) {
      $parentId = $id;
      break;
    }
  }
  if ( $parentId ) {
    break;
  }
}

或者有一个功能:

function searchParent($input, $childId) {
  foreach ( $input as $id => $parent ) {
    foreach ( $parent['children'] as $child ) {
      if ( $child['id'] == $childId ) {
        return $id;
      }
    }
  }
}

$parentId = searchParent($input, $childId);
于 2013-07-23T10:20:55.527 回答