簡體   English   中英

PHP - 將多維數組值添加到特定鍵的有效方法

[英]PHP - efficient way of adding multidimensional array values to a specific key

我有一個多維數組,其中包含一些基於用戶選擇從搜索中“查找”或“排除”過濾器的 ID。 每組過濾器都按一個鍵(在下面的示例中為 65)分組:

$cache_data = ['filters' => [
        65 => [
            'find' => [
                167
            ],
            'exclude' => [
                169,
                171
            ]
        ]
    ]
];

我想在find數組中添加更多 ID,同時保留任何已經存在的 ID:在這種情況下為 167。 exclude數組中的值需要保持不變。 假設我想添加以下 4 個值來find

$to_be_added = [241, 242, 285, 286];

我需要根據過濾器的組 ID(在本例中為 65)來定位過濾器,並使用array_merge()合並我的新值:

$existing_filters = ($cache_data['filters'][65]);
$merged = array_merge($existing_filters['find'], $to_be_added);

然后我通過使用$mergedfind鍵重寫$cache_data['filters'][65] ,並將已經存在的值保留在exclude

$cache_data['filters'][65] = [ 
        'find' => $merged,
        'exclude' => $existing_filters['exclude']
    ];

這個的輸出, print_r($cache_data['filters'][65]); 正是我想要的:

Array
(
    [find] => Array
        (
            [0] => 167
            [1] => 241
            [2] => 242
            [3] => 285
            [4] => 286
        )

    [exclude] => Array
        (
            [0] => 169
            [1] => 171
        )

)

但是我想知道是否有更簡單或更有效的方法來實現同樣的目標?

使用 PHP 7.2.10

單線:

$cache_data['filters'][65]['find'] = array_merge(
    $cache_data['filters'][65]['find'], 
    $to_be_added
);

使用

$cache_data['filters'][65]['find'] += $to_be_added;

不安全,因為在這種情況下,鍵0下的鍵值241將被忽略,因為$cache_data['filters'][65]['find']已經具有鍵0的值167

暫無
暫無

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

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