数组很有趣!
PHP有一个TON的数组函数,所以有很多潜在的解决方案.
我想出了这个作为个人挑战,它不使用循环,过滤器或地图.
此解决方案使用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