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