当前位置:Gxlcms > PHP教程 > php如何删除多维数组

php如何删除多维数组

时间:2021-07-01 10:21:17 帮助过:75人阅读

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

推荐:《PHP视频教程》

php删除多维数组里面的值

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

  1. <?php
  2. $arr = [
  3. 'test' => 'value',
  4. 'level_one' => [
  5. 'level_two' => [
  6. 'level_three' => [
  7. 'replace_this_array' => [
  8. 'special_key' => 'replacement_value',
  9. 'key_one' => 'testing',
  10. 'key_two' => 'value',
  11. 'four' => 'another value',
  12. ],
  13. ],
  14. 'ordinary_key' => 'value',
  15. ],
  16. ],
  17. ];
  18. $unset = array('special_key', 'ordinary_key', 'four');
  19. echo "<pre>";
  20. print_r(unsetMultiKeys($unset, $arr));
  21. print_r($arr);
  22. echo "</pre>";
  23. exit;
  24. function unsetMultiKeys($unset, $array) {
  25. $arrayIterator = new \RecursiveArrayIterator($array);
  26. $recursiveIterator = new \RecursiveIteratorIterator($arrayIterator, \RecursiveIteratorIterator::SELF_FIRST);
  27. foreach ($recursiveIterator as $key => $value) {
  28. foreach ($unset as $v) {
  29. if (is_array($value) && array_key_exists($v, $value)) {
  30. // 删除不要的值
  31. unset($value[$v]);
  32. // Get the current depth and traverse back up the tree, saving the modifications
  33. $currentDepth = $recursiveIterator->getDepth();
  34. for ($subDepth = $currentDepth; $subDepth >= 0; $subDepth--) {
  35. // Get the current level iterator
  36. $subIterator = $recursiveIterator->getSubIterator($subDepth);
  37. // If we are on the level we want to change, use the replacements ($value) other wise set the key to the parent iterators value
  38. $subIterator->offsetSet($subIterator->key(), ($subDepth === $currentDepth ? $value : $recursiveIterator->getSubIterator(($subDepth + 1))->getArrayCopy()));
  39. }
  40. }
  41. }
  42. }
  43. return $recursiveIterator->getArrayCopy();
  44. }

运行结果:

ae882ffd4c396033cd1faa0ebadad74.png

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

以上就是php如何删除多维数组的详细内容,更多请关注gxlcms其它相关文章!

人气教程排行