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

来源:互联网 发布:普陀区数据恢复 编辑:程序博客网 时间:2024/06/05 14:30
<?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();}
原创粉丝点击