Recursive search and remove in array?

泄露秘密 提交于 2019-12-01 19:21:24

You can ease things by only using references.

function removeKey($key, &$array, $childKey = 'children'){
    if(isset($array[$key])){
        unset($array[$key]);
        return;
    }

    foreach($array as &$item)
        if(isset($item[$childKey]))
            removeKey($key, $item[$childKey], $childKey);
}

Example:

$arr = array(...);
removeKey('key', $arr, $chilKey);
// Just continue using $arr

What about multidimensional array? I was researched for a couple of hours for this solution, nowhere found an optimal solution. so, i wrote it by myself

function allow_keys($arr, $keys)
    {
        $saved = [];

        foreach ($keys as $key => $value) {
            if (is_int($key) || is_int($value)) {
                $keysKey = $value;
            } else {
                $keysKey = $key;
            }
            if (isset($arr[$keysKey])) {

                $saved[$keysKey] = $arr[$keysKey];
                if (is_array($value)) {

                    $saved[$keysKey] = allow_keys($saved[$keysKey], $keys[$keysKey]);
                }
            }
        }
        return $saved;
    }

use: example

$array = [
        'key1' => 'kw',
        'loaa'=> ['looo'],
        'k'    => [
            'prope' => [
                'prop'  => ['proo', 'prot', 'loolooo', 'de'],
                'prop2' => ['hun' => 'lu'],
            ],
            'prop1' => [

            ],
        ],
    ];

call: example

allow_keys($array, ['key1', 'k' => ['prope' => ['prop' => [0, 1], 'prop2']]])

output:

Array ( [key1] => kw [k] => Array ( [prope] => Array ( [prop] => Array ( [0] => proo [1] => prot ) [prop2] => Array ( [hun] => lu ) ) ) ) 

so you get only needed keys from the multidimensional array. it is not limited only for "multidimensional", you can use it by passing an array like

['key1', 'loaa']

output you get:

Array ( [key1] => kw [loaa] => Array ( [0] => looo ) )

hope someone helps this one, as i searched a lot, and nothing found. cheers!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!