Home > Net >  Flatten an PHP Array to a simpler structure
Flatten an PHP Array to a simpler structure

Time:09-14

I have the following array structure from a database query: I extended my previous posts, with more details about the array structure. Hope that helps to better understand my example.

array:7 [▼
    0 => array:4 [▼
        0 => array:2 [▼
            "my_first_key" => "option 1"
            "SUMME" => "6"
        ]
        1 => array:2 [▼
            "my_first_key" => "option 2"
            "SUMME" => "22"
        ]
        2 => array:2 [▼
            "my_first_key" => "option 3"
            "SUMME" => "37"
        ]
        3 => array:2 [▼
            "my_first_key" => "option 4"
            "SUMME" => "42"
        ]
    ],
    0 => array:4 [▼
        0 => array:2 [▼
            "my_second_key" => "option 1"
            "SUMME" => "6"
        ]
        1 => array:2 [▼
            "my_second_key" => "option 2"
            "SUMME" => "22"
        ]
        2 => array:2 [▼
            "my_second_key" => "option 3"
            "SUMME" => "37"
        ]
        3 => array:2 [▼
            "my_second_key" => "option 4"
            "SUMME" => "42"
        ]
    ]
    ...
]

How can I transform it to a much simpler structure like:

array:8 [▼
    "my_first_key" => array:4 [▼
        "option 1" => "6"
        "option 2" => "22"
        "option 3" => "37"
        "option 4" => "42"
    ],
    "my_second_key" => array:4 [▼
        "option 1" => "6"
        "option 2" => "22"
        "option 3" => "37"
        "option 4" => "42"
    ]
    ...
]

I tried to give array_walk_recursive a try, but I can't grab the SUMME key and bind it to the previous option?

$tmpArr = [];
array_walk_recursive($data, static function ($value, $key) use (&$tmpArr) {
   $tmpArr[$key][$value] = $value; // not $value? SUMME here?
}, $tmpArr);

CodePudding user response:

You need to simple do it like below using foreach()

$tmpArr = [];
foreach($data as $dat){
    foreach($dat as $d){
        $key = array_keys($d)[0];
        $tmpArr[$key][$d[$key]] = $d['SUMME'];
    }
}

Output : https://3v4l.org/hmu5r

CodePudding user response:

If you want to use array_walk_recursive you can do it like this:

$output = [];
array_walk_recursive($arr, function ($item, $key) use (&$output) {
    if ($key === 'SUMME') {
        end($output);
        $a = key($output);
        end($output[$a]);
        $b = key($output[$a]);
        $output[$a][$b] = $item;
    } else {
        $output[$key][$item] = '';
    }
});
  • Related