dongyihang3575 2014-12-16 18:16
浏览 63
已采纳

PHP:如何通过指定从较大的数组中提取的一组键值来创建过滤的数组?

How can I create a smaller, filtered array based on a larger array. For example, this is the larger array:

$large_array = array(
    'user_email' => array(
        'required' => true,
        'email' => true,
        'max' => 200,
        'unique' => 'users'),
    'password' => array(
        'required' => true,
        'min' => 6,
        'max' => 20),
    'password_again' => array(
        'required' => true,
        'matches' => 'password'),
    'name_first' => array(
        'required' => false,
        'min' => 2,
        'max' => 64),
    'name_last' => array(
        'required' => false,
        'min' => 2,
        'max' => 64));

I want to create a filtered array based on the 'user_email' and 'name_first' keys from the large array. This filtered array would end up looking like this:

$filtered_array = array(
    'user_email' => array(
        'required' => true,
        'email' => true,
        'max' => 200,
        'unique' => 'users'),
    'name_first' => array(
        'required' => false,
        'min' => 2,
        'max' => 64);

What's the best way to do this in PHP? I'm trying to get a function that takes a set of keys and the $large_array to create the $filtered_array.

  • 写回答

1条回答 默认 最新

  • duanchen1937 2014-12-16 18:24
    关注

    Use array_filter with the ARRAY_FILTER_USE_KEY flag.

    Like so:

    $filtered_array = array_filter($myarr, function($key){
        $keys = array("key1", "key2");
        return in_array($key, $keys);
    }, ARRAY_FILTER_USE_KEY);
    

    If your php version is < 5.6.0 you won't be able to use the ARRAY_FILTER_USE_KEY flag and if your php version is < 5.3.0 you won't be able to use the anonymous function syntax, however you can simply create a named function and pass that name as a string for the callback parameter.

    Alternatively, this should do the same thing:

    function ($arr, $keys)
    {
        $newArr = array();
    
        foreach($arr as $key => $val)
        {
            if(in_array($key, $keys))
                $newArr[$key] = $val;
        }
    
        return $newArr;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?