Remove all array elements except what I want?

后端 未结 8 2020
挽巷
挽巷 2021-01-31 14:13

I have controller that takes post parameters from HTML form, it will then send them to model that will insert the array into Cassandra database.

It is SQLInjection proof

8条回答
  •  遥遥无期
    2021-01-31 14:45

    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 ) )
    

    cheers!

提交回复
热议问题