$word = array("red","or","bl","green","gr");
$colors = array( "re"=>"red" ,
"or"=>"orange",
"bc"=>"black" ,
"br" =>"brown",
"gr" =>"green"
);
//找到数组颜色的数组字的值,如果它的键或值无关紧要 //输出应显示键和值。
re =>红色
或=>橙
gr =>绿色
答案 0 :(得分:1)
这是一个从数组$ contains计算$ array的键和值的交集(?)的函数:
function array_full_intersect($array, $contains) {
$result = array();
// Go through each element in $contains.
foreach ($contains as $val) {
// If $val is a key in $array, add key-value pair to $result.
if (isset($array[$val])) {
$result[$val] = $array[$val];
} else {
// Otherwise, if $val is a value in $array, search for the value and get its key.
// Add key-value pair to $result.
$key = array_search($val, $array);
if ($key !== false) {
$result[$key] = $val;
}
}
}
return $result;
}
如果您更喜欢更紧凑的解决方案,请使用评论中描述的内容:
function array_full_intersect($array, $contains) {
return array_merge(array_intersect_key($array, array_flip($contains)), array_intersect($array, $contains));
}
用作:
$result = array_full_intersect($colors, $word);
答案 1 :(得分:1)
使用PHP数组函数:
$values = array_intersect($colors, $word);
$flip = array_flip($colors);
$flipValues = array_intersect($flip, $word);
$keys = array_flip($flipValues);
$result = array_merge($values, $keys);
将此分开:
创建一个数组,其中包含$ colors的所有成员,其值与$ word中的值相同,即
$values = array(
"re"=>"red",
"gr" =>"green"
);
2. $flip = array_flip($colors);
这会翻转$ colors的键和值,所以它是:
$flip = array( "red" => "re",
"orange" => "or",
"black" => "bc",
"brown" => "br",
"green" => "gr"
);
这再次使用array_intersect,但是在键上($ flip中的值)。所以这将是
$flip = array( "orange" => "or",
"green" => "gr"
);
4. $keys = array_flip($flipValues);
这又将结果翻了回来:
$keys= array( "or" => "orange",
"gr" => "green"
);
然后array_merge结合使用$ values和$ keys来消除重复项。