>  기사  >  백엔드 개발  >  PHP에서 다차원 배열을 삭제하는 방법

PHP에서 다차원 배열을 삭제하는 방법

藏色散人
藏色散人원래의
2020-10-13 10:02:092888검색

PHP에서 다차원 배열을 삭제하는 방법: 먼저 PHP 샘플 파일을 만든 다음 unsetMultiKeys 메서드를 통해 복잡한 다차원 배열에서 지정된 키-값 쌍을 삭제하고 마지막으로 실행 결과를 확인합니다.

PHP에서 다차원 배열을 삭제하는 방법

추천: "PHP Video Tutorial"

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(); }

작업 결과:

PHP에서 다차원 배열을 삭제하는 방법

다차원 배열의 키-값 쌍 변경

위 내용은 PHP에서 다차원 배열을 삭제하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.