This is an example of array I have:
$data = [
'total_amount' => 200,
'purchase_date' => '01.01.2020',
'items' => [
[
'name' => 'T-shirt',
'price' => 50
],
[
'name' => 'Jacket',
'price' => 150
],
]
];
and I would like to get something like this:
$data = [
[
'k' => 'total_amount',
'v' => 200
],
[
'k' => 'purchase_date',
'v' => '01.01.2020'
]
[
'k' => 'items',
'v' => [
[
[
'k' => 'name',
'v' => 'T-Shirt'
],
[
'k' => 'price',
'v' => 50
]
],
[
[
'k' => 'name',
'v' => 'Jacket'
],
[
'k' => 'price',
'v' => 150
]
]
]
]
]
It's not a big problem to parse the first array and then create desired output. Also, if we have nested and nasted and nested array, then I just use a recursion and it seems to work pretty good. Here is the code I have:
public function convert(array $data) : array
{
$output = [];
foreach ($data as $k => $v) {
if (is_array($v)) {
$output[] = ['k' => $k, 'v' => $this->value($v)];
} else {
$output[] = ['k' => $k, 'v' => $v];
}
}
return $output;
}
and the following:
protected function value($items)
{
$output = [];
$i = 0;
foreach ($items as $itemK => $itemV) {
if (!is_array($itemV)) {
$output[$i] = ['k' => $itemK, 'v' => $itemV];
continue;
}
foreach ($itemV as $k => $v) {
if (is_array($v)) {
$output[$i][] = ['k' => $k, 'v' => $this->value($v)];
continue;
}
$output[$i][] = ['k' => $k, 'v' => $v];
}
$i++;
}
return $output;
}
The question is if there is a way to optimize this code without using too many foreach functions (maybe there is built-in PHP function that I can leverage) and maybe avoid recursion?