Flattening a JSON multi depty array in PHP

后端 未结 2 802
挽巷
挽巷 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: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);
    

提交回复
热议问题