牛骨文教育服务平台(让学习变的简单)
博文笔记

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

创建时间:2017-06-26 投稿人: 浏览次数:735
<?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();
}
声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。