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

根据关键密钥将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);

图片转代码服务由CSDN问答提供 功能建议

如果我想在第一个结果数组中保留键,如何将关联数组拆分为两个数组? ?

例如......

  //给定:
 $ myArray = array('a'=> 123,  'b'=> 'ABC', 'C'=> 321, 'd'=> 'CBA', 'E'=> 111); 
 $的分裂=阵列( '一个','C  '); 
 
 //获取所有元素的键是$ split 
 $ newArray1 = array('a'=> 123,'c'=> 321); 
 //获取所有元素 密钥不在$ 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()

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题