dongqishun6409 2014-06-20 14:26
浏览 114
已采纳

根据关键密钥将PHP数组拆分为两个数组

How do I split an associate array into two arrays given the keys that I would like to keep in the first resultant array?

For instance...

//Given:
$myArray=array('a'=>123,'b'=>'ABC','c'=>321,'d'=>'CBA','e'=>111);
$split=array('a','c');

//Obtain all elements who's keys are in $split
$newArray1=array('a'=>123,'c'=>321);
//Obtain all elements who's keys are not in $split
$newarray2=array('b'=>'ABC','d'=>'CBA','e'=>111);
  • 写回答

1条回答 默认 最新

  • dsgdhtr_43654 2014-06-20 14:29
    关注

    No frills:

    $newArray1 = [];
    $newArray2 = [];
    
    foreach ($myArray as $key => $value) {
        if (in_array($key, $split)) {
            $newArray1[$key] = $value;
        } else {
            $newArray2[$key] = $value;
        }
    }
    

    Frills:

    $newArray1 = array_intersect_key($myArray, array_flip($split));
    $newArray2 = array_diff_key($myArray, $newArray1);
    

    See also: array_intersect_key() array_flip() array_diff_key()

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

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