Example input as json
{
"user":{
"name":"Thomas",
"age":101
},
"shoppingcart":{
"products":{
"p1":"someprod",
"p2":"someprod2"
},
"valuta":"eur",
"coupon":null,
"something":[
"bla1",
"bla2"
]
}
}
Expected output
[
'user.name' => 'Thomas',
'user.age' => 101,
'shoppingcart.products.p1' => 'someprod',
...
'shoppingcart.something.1' => 'bla1'
]
I have written this function however it produces the wrong output. Next to that, I would like to rewrite said function to a macro for Collection
but I cannot wrap my head around it. The problem is also that the current function as is requires a global var to keep track of the result.
public function dotFlattenArray($array, $currentKeyArray = []) {
foreach ($array as $key => $value) {
$explodedKey = preg_split('/[^a-zA-Z]/', $key);
$currentKeyArray[] = end($explodedKey);
if (is_array($value)) {
$this->dotFlattenArray($value, $currentKeyArray);
} else {
$resultArray[implode('.', $currentKeyArray)] = $value;
array_pop($currentKeyArray);
}
}
$this->resultArray += $resultArray;
}
So my problem is twofold: 1. Sometimes the function does not give the right result 2. How can I rewrite this recursive function to a macro
Collection::macro('dotflatten', function () {
return ....
});