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

时间:2019-03-19 11:21:22

标签: php arrays

我有一个多维数组,其中包含一些ID,这些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

1 个答案:

答案 0 :(得分: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']已经具有键{{1} },其值为0