我有以下方法用于递归构建我的php数组,然后将它们转换为json字符串:
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;
}
}
编辑:这就是它的名称:
$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']);
}
然后在这之后只需json_encode就像json_encode($ path_arr) 结束编辑 问题是格式化如果到达第二级应使用数组来包装部件。所以我现在得到的是:
{
"product_title":"Test Title",
"ASIN":"1234567890",
"codes":{
"type":"UPC",
"number":"030878249270"
},
"quantity":"1"
}
我需要的是以下内容:
{
"product_title":"Test Title",
"ASIN":"1234567890",
"codes":[
{
"type":"UPC",
"number":"030878249270"
}
],
"quantity":"1"
}
关于如何使用递归方法执行此操作的任何想法?
答案 0 :(得分:2)
鉴于问题和评论中陈述的(非常)具体条件:
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(array());
}
$this->stringKeyToMultArray($newarr[$key][0], $keys, $value);
} else {
$newarr[array_shift($keys)] = $value;
}
}