簡體   English   中英

PHP 基於鍵未設置數組值

[英]PHP unset array value based on key

我有如下多維數組,

[0] => Array
    (
        [data] => 
        [id] => 0000
        [name] => Swirl
        [categories] => Array
            (
                [0] => Array
                    (
                        [id] => 0001
                        [name] => Whirl
                        [products] => Array 
                           (
                                [0] => Array
                                    (
                                        [id] => 0002
                                        [filename] => 1.jpg
                                     )
                                [1] => Array
                                    (
                                        [id] => 0003
                                        [filename] => 2.jpg
                                     )
                            )
                     )
             )
      )

我使用以下 function 來查找密鑰。

function find_parent($array, $needle, $parent = null) {
    foreach ($array as $key => $value) {
        if (is_array($value)) {
            $pass = $parent;
            if (is_string($key)) {
                $pass = $key;
            }
            $found = find_parent($value, $needle, $pass);
            if ($found !== false) {
                return $found;
            }
        } else if ($key === $needle) {
            return $parent;
        }
    }

    return false;
}

$parentkey = find_parent($array, 'id');

現在我需要取消設置 products 數組並將其替換為另一個數組。

如何做到這一點。請幫忙。

謝謝,薩尼莎

您可以在數組上使用遞歸 function:

function replaceInArray(array &$arr, $needleKey, array $replacement) {
  foreach ($arr as $k => $v) {
    if ($k === $needleKey) {
        $arr[$k] = $replacement;
    } else {
        if (is_array($v)) {
            replaceInArray($arr[$k], $needleKey, $replacement);
        }
    }
  }
}

replaceInArray($sourceArr, 'products', ['id' => '0004', 'filename' => 'new.jpg']);

function replaceInArrayWithKey(array &$arr, $needleKey, array $replacementArray, $replacementKey) {
  foreach ($arr as $k => $v) {
    if ($k === $needleKey) {
        $arr[$replacementKey] = $replacementArray;
        unset($arr[$k]);
    } else {
        if (is_array($v)) {
            replaceInArrayWithKey($arr[$k], $needleKey, $replacementArray, $replacementKey);
        }
    }
  }
}

replaceInArrayWithKey($sourceArray, 'products', ['id' => '0004', 'filename' => 'new.jpg'], 'products_new');

您也可以嘗試使用內置的遞歸迭代器 - https://www.php.net/manual/en/class.recursivearrayiterator.php

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM