PHP - 将多维数组值添加到特定键的有效方法

问题描述 投票:2回答:1

我有一个多维数组,其中包含一些基于用户选择从搜索中“查找”或“排除”的过滤器的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);

然后我使用$cache_data['filters'][65]$merged键重写find,并保留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

php arrays
1个回答
1
投票

oneLiner:

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

运用

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

是不安全的,因为在这种情况下,密钥241下的密钥值0将被忽略,因为$cache_data['filters'][65]['find']已经具有值为0的密钥167

© www.soinside.com 2019 - 2024. All rights reserved.