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

时间:2014-06-20 14:26:36

标签: php arrays

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

例如......

//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 个答案:

答案 0 :(得分:10)

没有多余的装饰:

$newArray1 = [];
$newArray2 = [];

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

褶边:

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

另请参阅:array_intersect_key() array_flip() array_diff_key()