简体   繁体   中英

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. Each set of filters is grouped by a key (65 in the example below):

$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. The values in the exclude array need to remain untouched. Assume I want to add the following 4 values to 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() :

$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 :

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

The output for this, 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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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