Flattening a JSON multi depty array in PHP

后端 未结 2 778
挽巷
挽巷 2021-01-14 11:38

Good morning, given the below data structure (in JSON for ease of reading)

[
{
    \"parent\": \"root\",
    \"active\": \"1\",
    \"label\": \"Index\",
            


        
相关标签:
2条回答
  • 2021-01-14 11:54

    Not very hard:

    function flatten(array $array) {
        $branch = [];
    
        foreach ($array as $item) {
            $children = [];
            if (isset($item['children']) && is_array($item['children'])) {
                $children = flatten($item['children']);
                unset($item['children']);
            }
            $branch = array_merge($branch, [$item], $children);
        }
    
        return $branch;
    }
    
    0 讨论(0)
  • 2021-01-14 11:56

    Easy-peasy

    function flatten($items, &$r) {
        foreach($items as $item) {
            $c = isset($item->children) ? $item->children : null;
            unset($item->children);
            $r []= $item;
            if($c)
                flatten($c, $r);
        }
    }
    
    flatten(json_decode($json), $r);
    print_r($r);
    

    This accumulates results in one single buffer, passed by reference. This is far more efficient than building a whole new array on each iteration, which is basically a variation of the Shlemiel the painter's algorithm.

    If you prefer functional approach, you can use generators:

    function flatten($items) {
        foreach($items as $item) {
            $c = isset($item->children) ? $item->children : [];
            unset($item->children);
            yield $item;
            foreach(flatten($c) as $child)
                yield $child;
        }
    }
    
    foreach(flatten(json_decode($json)) as $item)
        print_r($item);
    
    0 讨论(0)
提交回复
热议问题