【问题标题】:Find latest children in nested categories php在嵌套类别 php 中查找最新的子项
【发布时间】:2021-02-04 10:40:07
【问题描述】:

我尝试使用来自 url 的 PHP 解析 JSON。我需要一个没有子项的项目列表 - 意味着 children 字段应该是空数组,parent_id 不应该是 0 - 意味着不是父母。

JSON:

{
  "body": {
    "data": [
      {
        "id": 1,
        "name": "car",
        "parent_id": "0",
        "children": [
          {
            "id": 2,
            "name": "bmw",
            "parent_id": "1",
            "children": [
              {
                "id": 4,
                "name": "bmw i8",
                "parent_id": "2",
                "children": []
              }
            ]
          },
          {
            "id": 3,
            "name": "mustang",
            "parent_id": "1",
            "children": []
          }
        ]
      },
      {
        "id": 5,
        "name": "clothes",
        "parent_id": "0",
        "children": []
      },
      {
        "id": 6,
        "name": "mobile",
        "parent_id": "0",
        "children": [
          {
            "id": 7,
            "name": "apple",
            "parent_id": "6",
            "children": [
              {
                "id": 9,
                "name": "Iphone 12 pro",
                "parent_id": "7",
                "children": []
              },
              {
                "id": 10,
                "name": "Iphone 11",
                "parent_id": "7",
                "children": []
              }
            ]
          },
          {
            "id": 8,
            "name": "Xiaomi",
            "parent_id": "6",
            "children": []
          }
        ]
      }
    ]
  }
}

预期输出:

[4,3,9,10,8]

这是我尝试过但不起作用的 php 代码。

    $CategoryUrl = file_get_contents(self::CATEGORY_URL,true);
    $array = json_decode($CategoryUrl,true);
    $list = array();
    foreach( $array['body']['data'] as $value ){
        if (($value['parent_id'] != 0) && empty($value['children'])) { 
            foreach( $value['children'] as $val ){
                    $list[] = $val;
            }
        }
    }

    print_r($list);

【问题讨论】:

  • 这能回答你的问题吗? How to use array_walk_recursive
  • 有点相似,但对我没有帮助。 @nice_dev
  • 它提供了通用机制——递归遍历整个数组正是您所需要的。你只需要修改回调。

标签: php arrays multidimensional-array


【解决方案1】:

使用array_walk_recursive 跟踪父 ID 值和子调用确实有点棘手,因为它直接跳转到其子代。但是,这仍然可以使用您自己的递归版本来完成,如下所示。继续检查parent_idchildren 计数。如果两个约束都满足,则将它们添加到$result,否则继续递归调用children

<?php

$str = '{"body":{"data":[{"id":1,"name":"car","parent_id":"0","children":[{"id":2,"name":"bmw","parent_id":"1","children":[{"id":4,"name":"bmw i8","parent_id":"2","children":[]}]},{"id":3,"name":"mustang","parent_id":"1","children":[]}]},{"id":5,"name":"clothes","parent_id":"0","children":[]},{"id":6,"name":"mobile","parent_id":"0","children":[{"id":7,"name":"apple","parent_id":"6","children":[{"id":9,"name":"Iphone 12 pro","parent_id":"7","children":[]},{"id":10,"name":"Iphone 11","parent_id":"7","children":[]}]},{"id":8,"name":"Xiaomi","parent_id":"6","children":[]}]}]}}';


$data = json_decode($str,true);
$result = [];


function walkRecursive($data,&$result){
    foreach($data as $entry){
        if($entry['parent_id'] != 0 && count($entry['children']) == 0){
            $result[] = $entry['id'];
        }else{
            walkRecursive($entry['children'],$result);
        }
    }
}

walkRecursive($data['body']['data'],$result);
print_r($result);

【讨论】:

    【解决方案2】:

    我们可以通过函数调用递归算法来解决这个问题, 希望你清楚

    $CategoryUrl = file_get_contents(self::CATEGORY_URL,true);
    $array = json_decode($CategoryUrl, true);
    $items = $array['body']['data'];
    $list = [];
    
    findParentIds(items, $list);
    
    // doSomething 
    
    print_r($list);
    
    
    /**
     * passe by ref (list)
     * @param array $children
     * @param $list
     */
    function findParentIds(array $children, & $list)
    {
        foreach ($children as $child) {
    
            // use case 1: has no children and parent_id is 0 , just continue
            if (empty($child['children']) && $child['parent_id'] == "0") {
                continue;
            }
            // use case 2: has no children and parent_id is 0 , it's parent item
            if (empty($child['children']) && $child['parent_id'] != "0") {
                array_push($list, $child['id']);
    
            }
    
            // has children and parent_id is not 0 , recall function to treat use case 1 and 2 ..
            findParentIds($child['children'], $list);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-04-05
      • 2019-09-18
      • 1970-01-01
      • 2018-09-10
      • 1970-01-01
      • 1970-01-01
      • 2013-08-22
      • 2010-09-21
      • 1970-01-01
      相关资源
      最近更新 更多