PHP8.1.21版本已发布
vue8.1.21版本已发布
jquery8.1.21版本已发布

php如何删除多维数组

藏色散人
藏色散人 原创
2020-10-13 10:02:09 2729浏览

php删除多维数组的方法:首先创建一个php示例文件;然后通过unsetmultikeys方法删除复杂的多维数组里面的指定键值对;最后查看运行结果即可。

推荐:《PHP视频教程

php删除多维数组里面的值

在手册里面发现,改造后变成了一个函数,可以删除复杂的多维数组里面的制定键值对!

<?php
$arr = [
    &#39;test&#39; => &#39;value&#39;,
    &#39;level_one&#39; => [
        &#39;level_two&#39; => [
            &#39;level_three&#39; => [
                &#39;replace_this_array&#39; => [
                    &#39;special_key&#39; => &#39;replacement_value&#39;,
                    &#39;key_one&#39; => &#39;testing&#39;,
                    &#39;key_two&#39; => &#39;value&#39;,
                    &#39;four&#39; => &#39;another value&#39;,
                ],
            ],
            &#39;ordinary_key&#39; => &#39;value&#39;,
        ],
    ],
];
$unset = array(&#39;special_key&#39;, &#39;ordinary_key&#39;, &#39;four&#39;);
echo "<pre class="brush:php;toolbar:false">";
print_r(unsetMultiKeys($unset, $arr));
print_r($arr);
echo "
"; exit; function unsetMultiKeys($unset, $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]);                 // Get the current depth and traverse back up the tree, saving the modifications                 $currentDepth = $recursiveIterator->getDepth();                 for ($subDepth = $currentDepth; $subDepth >= 0; $subDepth--) {                     // Get the current level iterator                     $subIterator = $recursiveIterator->getSubIterator($subDepth);                     // If we are on the level we want to change, use the replacements ($value) other wise set the key to the parent iterators value                     $subIterator->offsetSet($subIterator->key(), ($subDepth === $currentDepth ? $value : $recursiveIterator->getSubIterator(($subDepth + 1))->getArrayCopy()));                 }             }         }     }     return $recursiveIterator->getArrayCopy(); }

运行结果:

ae882ffd4c396033cd1faa0ebadad74.png

改变多维数组里面的键值对

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。