我想比较两个平面索引数组的值并生成一个新数组,其中键是第一个数组的原始值,值是 boolean 值,指示两个原始数组中是否出现相同的值。
$array1 = [
"car1",
"car2",
"car3",
"car4",
"car5"
];
$array2 = [
"car1",
"car4",
"car5"
}
我尝试用 array_diff()
函数比较数组,但它给了我元素值而不是 boolean 值。
我想比较两个数组中的每个值并生成“数组映射”或者可能使用 array_combine()
函数来获取这样的数组:
[
"car1" => true,
"car2" => false,
"car3" => false
"car4" => true,
"car5" => true,
]
最佳答案
数组很有趣!
PHP 有大量的数组函数,因此有很多潜在的解决方案。
我想出这个作为个人挑战,它不使用循环、过滤器或映射。
此解决方案使用 array_intersect找到两个数组中都存在的值,然后 array_values连同 array_fill_keys将它们变成填充有 TRUE
或 FALSE
的关联数组,最后是 array_merge将它们放在一个数组中:
$array1 = array( 0 => "car1", 1 => "car2", 2 => "car3", 3 => "car4", 4 => "car5");
$array2 = array( 0 => "car1", 1 => "car4", 2 => "car5" );
// Find all values that exist in both arrays
$intersect = array_intersect( $array1, $array2 );
// Turn it into an associative array with TRUE values
$intersect = array_fill_keys( array_values($intersect), TRUE );
// Turn the original array into an associative array with FALSE values
$array1 = array_fill_keys( array_values( $array1 ), FALSE );
// Merge / combine the arrays - $intersect MUST be second so that TRUE values override FALSE values
$results = array_merge( $array1, $intersect );
var_dump( $results );
结果:
array (size=5)
'car1' => boolean true
'car2' => boolean false
'car3' => boolean false
'car4' => boolean true
'car5' => boolean true
关于php - 比较两个数组并创建一个真/假值的关联数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40775604/