您的位置:首页 > 编程语言 > PHP开发

php批量处理多维数组替换,删除部分键值

2017-06-26 10:43 555 查看
<?php
$arr1 = json_decode(file_get_contents('D:/phpStudy/WWW/mfstudy.com/mfxxapi/saveCarDetail.json'), true);

$unset = array('initial', 'salestate', 'depth');
echo "<pre>";
print_r(unsetMultiKeys($unset, 'logo', 'default.png', $arr1));
print_r($arr1);
echo "</pre>";
exit;

/**
* 批量删除替换多维数组里面不需要的数组键值
* @param  array $unset  不需要的键名数组
* @param  string $needle 需要被替换的键名下标
* @param  string $change 需要换成的键值,本例中logo为空的替换为default.png
* @param  array $array  需要被处理的数组
* @return array         返回被处理好的数组
*/
function unsetMultiKeys($unset, $needle, $change, $array) {
$arrayIterator = new \RecursiveArrayIterator($array);
$recursiveIterator = new \RecursiveIteratorIterator($arrayIterator, \RecursiveIteratorIterator::SELF_FIRST);
foreach ($recursiveIterator as $key => $value) {
foreach ($unset as $v) {
if (is_array($value) && array_key_exists($v, $value)) {
// 删除不要的值
unset($value[$v]);
}
}
if (is_array($value) && array_key_exists($needle, $value)) {
if (empty($value[$needle])) {
$value[$needle] = $change;
}
}
// 获取当前层级深度,以备后面返回, 保存修改
$currentDepth = $recursiveIterator->getDepth();
for ($subDepth = $currentDepth; $subDepth >= 0; $subDepth--) {
// 获取当前层级迭代器
$subIterator = $recursiveIterator->getSubIterator($subDepth);
// 如果我们在想要改变的那个层级,就可以进行删除操作了,最后返回的的是复制的数组
$subIterator->offsetSet($subIterator->key(), ($subDepth === $currentDepth ? $value : $recursiveIterator->getSubIterator(($subDepth + 1))->getArrayCopy()));
}
}
return $recursiveIterator->getArrayCopy();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  php