简体   繁体   English

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

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

I have a multi-dimensional array which contains some ID's based on filters a user has chosen to "find" or "exclude" from a search.我有一个多维数组,其中包含一些基于用户选择从搜索中“查找”或“排除”过滤器的 ID。 Each set of filters is grouped by a key (65 in the example below):每组过滤器都按一个键(在下面的示例中为 65)分组:

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

I want to add some more ID's to the find array whilst retaining any that are already there: 167 in this case.我想在find数组中添加更多 ID,同时保留任何已经存在的 ID:在这种情况下为 167。 The values in the exclude array need to remain untouched. exclude数组中的值需要保持不变。 Assume I want to add the following 4 values to find :假设我想添加以下 4 个值来find

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

I need to target the filters based on their group ID (65 in this case) and merge in my new values using array_merge() :我需要根据过滤器的组 ID(在本例中为 65)来定位过滤器,并使用array_merge()合并我的新值:

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

I then rewrite $cache_data['filters'][65] by using $merged with the find key, and keep the values that were already there in exclude :然后我通过使用$mergedfind键重写$cache_data['filters'][65] ,并将已经存在的值保留在exclude

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

The output for this, print_r($cache_data['filters'][65]);这个的输出, print_r($cache_data['filters'][65]); is exactly as I want:正是我想要的:

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

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

)

However I'm wondering if there is an easier or more efficient way to achieve the same thing?但是我想知道是否有更简单或更有效的方法来实现同样的目标?

Using PHP 7.2.10使用 PHP 7.2.10

Oneliner:单线:

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

Using使用

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

is not safe because in this case key value 241 which is under key 0 will be ignored, as $cache_data['filters'][65]['find'] already has key 0 with value 167 .不安全,因为在这种情况下,键0下的键值241将被忽略,因为$cache_data['filters'][65]['find']已经具有键0的值167

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM