在PHP数组中查找父级

时间:2013-07-23 10:16:21

标签: php arrays

我有以下数组,我唯一的值是子页面的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
                    )

            )

    )

有没有人有这方面的好解决方案?

提前致谢。

3 个答案:

答案 0 :(得分:0)

尝试:

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

但是 - 这只会返回包含身份$you_look_for的子项的数组的第一个id。

答案 1 :(得分: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);

答案 2 :(得分:0)

构建数组时(假设您是自己创建数组),添加对父项的引用:

<?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
?>

这允许您使用childsparent条目“非常流畅地”遍历数组。 (基本上它是一棵树,然后)