gpt4 book ai didi

php - 根据关联键将PHP数组拆分为两个数组

转载 作者:行者123 更新时间:2023-12-04 14:40:56 28 4
gpt4 key购买 nike

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

例如...

//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()

关于php - 根据关联键将PHP数组拆分为两个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24329574/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com