给定要保留在第一个结果数组中的键,如何将一个关联数组分成两个数组?
例如...
//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);
最佳答案
没有多余的装饰:
$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()