我有这样一个需求,下面我以json格式展示便于查看结构。我需要删除多维数组中的空字段/指定字段,并且修改某些字段的键名称。
[
{
"_id":1,
"name":"笔记本整机",
"tag":"",
"list":[
{
"_id":19,
"name":"笔记本",
"tag":"",
"list":[
{
"_id":75,
"name":"笔记本电脑",
"tag":"notebook",
"list":[
]
},
{
"_id":86,
"name":"电脑锁",
"tag":"notebook_lock",
"list":[
]
}
]
},
{
"_id":20,
"name":"平板产品",
"tag":"",
"list":[
{
"_id":87,
"name":"平板电脑",
"tag":"tablepc",
"list":[
]
},
{
"_id":94,
"name":"其它配件",
"tag":"other_accessories",
"list":[
]
}
]
}
]
},
{
"_id":2,
"name":"手机",
"tag":"",
"list":[
{
"_id":22,
"name":"手机",
"tag":"",
"list":[
{
"_id":105,
"name":"手机",
"tag":"cell_phone",
"list":[
]
},
{
"_id":115,
"name":"号卡专区",
"tag":"haoka",
"list":[
]
}
]
},
{
"_id":23,
"name":"通讯产品",
"tag":"",
"list":[
{
"_id":116,
"name":"集团电话",
"tag":"groupphone",
"list":[
]
},
{
"_id":124,
"name":"呼叫器",
"tag":"beeper",
"list":[
]
}
]
}
]
}
]
需求:
- 删除多维数组中
tag
、list
键值为空的 - 修改
_id
键为id
键、修改list
键为child
键
正确格式如下json
[
{
"id":1,
"name":"笔记本整机",
"child":[
{
"id":19,
"name":"笔记本",
"child":[
{
"id":75,
"name":"笔记本电脑"
},
{
"id":86,
"name":"电脑锁"
}
]
},
{
"id":20,
"name":"平板产品",
"child":[
{
"id":87,
"name":"平板电脑"
},
{
"id":94,
"name":"其它配件"
}
]
}
]
},
{
"id":2,
"name":"手机",
"child":[
{
"id":22,
"name":"手机",
"child":[
{
"id":105,
"name":"手机"
},
{
"id":115,
"name":"号卡专区"
}
]
},
{
"id":23,
"name":"通讯产品",
"child":[
{
"id":116,
"name":"集团电话"
},
{
"id":124,
"name":"呼叫器"
}
]
}
]
}
]
php代码如下
<?php
/**
* @param array $arr 原数组
*
* 修改前的_id键对应修改后的id,修改前的list键对应修改后的child
*
* @param array $editKey =>['_id' => 'id', 'list' => 'child']
*
* tag 键为true时,全部删除,list 键为false时,仅仅删除为空的数组或者字段
* @param array $delKey =>['tag' => true, 'list' => false]
*
* @return array
*/
function array_filter_recursive(array &$arr, array $editKey, array $delKey)
{
if (count($arr) < 1) {
return [];
}
foreach ($arr as $k => $v) {
if (is_array($v)) {
$arr[$k] = $this->array_filter_recursive($v, $editKey, $delKey);
}
$key = '';
if (in_array($k, array_keys($editKey), true)) {//要修改的key
$arr[$editKey[$k]] = $arr[$k];
$key = $editKey[$k];
unset($arr[$k]);
}
//要删除的key
if (in_array($k, array_keys($delKey), true)) {
if (!$delKey[$k] && (is_null($arr[$key]) || empty($arr[$key])) && $key) {//只删除为空的
unset($arr[$key]);
} else {
if ($delKey[$k]) {//全删除
unset($arr[$k]);
}
}
}
}
return $arr;
}
?>