How to get a subset of $_POST array with keys starting with a prefix

前端 未结 8 1517
栀梦
栀梦 2020-12-31 13:18

Let\'s say my $_POST variable looks like:

 65
    [action] => editpost
    [originalaction] => editpo         


        
8条回答
  •  伪装坚强ぢ
    2020-12-31 14:01

    Here's a cool ultra-php-neat way to use php array_walk to specify a generic prefix to remove:

    $foo = array('k_foo' =>"bar", 
                  'k_bar' =>"b0r", 
                  'y_foo' =>"b5r",
                  'y_not' =>"b7r", 
                 'k_not' =>"b1r");
    
    $subsetArray = $foo;
    $key_prefix = "k_";
    
    array_walk($foo, 'removeUnwanted', array(&$subsetArray, $key_prefix));
    var_dump ($subsetArray);
    
    function removeUnwanted($value, $key, $array){
        $prefix = $array[1];
        $testArray = &$array[0];
        if(strpos($key,$prefix) ===0){
            unset($testArray[$key]); 
        } 
    }
    

    Now you can just call array walk, with a copy of the array of values, and the prefix string.

提交回复
热议问题