I have the following method that I use to recursively build my php arrays then turn them into a json string:
protected function stringKeyToMultArray(&$newarr, $keys, $value) {
if(count($keys) > 1) {
$key = array_shift($keys);
if(!isset($newarr[$key]) || !is_array($newarr[$key])) {
$newarr[$key] = array();
}
$this->stringKeyToMultArray($newarr[$key], $keys, $value);
} else {
$newarr[array_shift($keys)] = $value;
}
}
EDIT: This is how it is called:
$path_arr = [];
foreach ($product_row['fields'] as $field) {
//gets the path for this field like pathto/field
$strpath = $tags[$field['id']]['str_path'];
$paths = explode('/', $strpath);
$this->stringKeyToMultArray($path_arr, $paths, $field['value']);
}
Then after this is simply json_encode it like json_encode($path_arr) END EDIT The issue is the formatting if it gets to a second level should use an array to wrap the parts. So what I am getting now is:
{
"product_title":"Test Title",
"ASIN":"1234567890",
"codes":{
"type":"UPC",
"number":"030878249270"
},
"quantity":"1"
}
What I need is the following:
{
"product_title":"Test Title",
"ASIN":"1234567890",
"codes":[
{
"type":"UPC",
"number":"030878249270"
}
],
"quantity":"1"
}
Any ideas on how I could do this with the recursive method?
$strpath = $tags[$field....is that really $strpath or$jetpath? And if it's not $jetpath, then where does$jetpathcome from?