【问题标题】:Finding parent in PHP Array在 PHP 数组中查找父级
【发布时间】:2013-07-23 10:16:20
【问题描述】:

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

            )

    )

有人对此有好的解决方案吗?

提前致谢。

【问题讨论】:

  • 您尝试过任何方法吗?看起来您正在寻找一个非常基本的(递归)循环(函数)
  • 如果您生成数组,只需将 reference 添加到父级:$parent = array(); $child= array(); $child["parent"] = &$parent; $parent[] = $child - 然后您可以从每个子级“向上”。并且不需要通过搜索整个数组来确定父级。最重要的是,将父级设置为null ofc。
  • @dognose 避免无用计算的好方法。

标签: php arrays


【解决方案1】:

试试:

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 的子代。

【讨论】:

    【解决方案2】:

    尝试:

    $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);
    

    【讨论】:

      【解决方案3】:

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

      <?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 条目“非常顺利”地遍历数组。 (基本上它是一棵树,那么)

      【讨论】:

      • 我不是在构建这个数组。它是由我正在尝试修改的 Magento 扩展构建的。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-01-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多