Home >Backend Development >PHP Problem >How to delete multidimensional array in php
php method to delete a multi-dimensional array: first create a PHP sample file; then delete the specified key-value pairs in the complex multi-dimensional array through the unsetMultiKeys method; finally check the running results.
Recommended: "PHP Video Tutorial"
php deletes values in multi-dimensional arrays
I found in the manual that after the transformation, it became a function that can delete specified key-value pairs in complex multi-dimensional arrays!
<?php $arr = [ 'test' => 'value', 'level_one' => [ 'level_two' => [ 'level_three' => [ 'replace_this_array' => [ 'special_key' => 'replacement_value', 'key_one' => 'testing', 'key_two' => 'value', 'four' => 'another value', ], ], 'ordinary_key' => 'value', ], ], ]; $unset = array('special_key', 'ordinary_key', 'four'); 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(); }
Run result:
Change the key-value pairs in the multi-dimensional array
The above is the detailed content of How to delete multidimensional array in php. For more information, please follow other related articles on the PHP Chinese website!