使用 PHP 数组函数:
$values = array_intersect($colors, $word);
$flip = array_flip($colors);
$flipValues = array_intersect($flip, $word);
$keys = array_flip($flipValues);
$result = array_merge($values, $keys);
把它拆开:
- $values = array_intersect($colors, $word);
创建一个包含所有 $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"
);
- $flipValues = array_intersect($flip, $word);
这再次使用了array_intersect,但在键(即$flip 中的值)上。所以这将是
$flip = array( "orange" => "or",
"green" => "gr"
);
4. $keys = array_flip($flipValues);
这会将结果再次翻转:
$keys= array( "or" => "orange",
"gr" => "green"
);
然后 array_merge 结合 $values 和 $keys 消除重复。