<?php
$tiger = array ("orange", "white");
$cat = array ("black", "white", "brown");
$fruit = array ("purple", "red", "green", "brown");
?>
如何输出如下内容:
orange : tiger
white : tiger + cat
black : cat
brown : cat + fruit
purple : fruit
答案 0 :(得分:5)
数组有点乐趣:
$arrays = compact('tiger', 'cat', 'fruit');
$values = array_unique(call_user_func_array('array_merge_recursive', $arrays));
foreach ($values as $value) {
$found = array();
foreach ($arrays as $name => $bag) {
if (in_array($value, $bag)) {
$found[] = $name;
}
}
echo "$value: ".implode(", ", $found)."\n";
}
通过修改第一行,您可以将其扩展到任意数量的数组。
<强> See it in action 强>
答案 1 :(得分:2)
所以看起来你有兴趣拍摄各种物体的颜色,然后切换关联,使颜色反射物体,而不是反过来。
以下是一种适用于您的方案的方法:
<?php
// The objects we wish to extract colors for
$subjects = array(
'tiger' => array ("orange", "white"),
'cat' => array ("black", "white", "brown"),
'fruit' => array ("purple", "red", "green", "brown")
);
// The array we will push colors to as keys, and objects to as values
$consolidated = array();
// Iterate over each object
foreach($subjects as $subject => $colors) {
// Iterate over each color in the object
foreach($colors as $color) {
$consolidated[$color][] = $subject;
}
}
// Print out results.
foreach($consolidated as $subject => $contents) {
print $subject . ' : ' . implode(' + ', $contents) . "<br />\n";
}
以上输出:
orange : tiger
white : tiger + cat
black : cat
brown : cat + fruit
purple : fruit
red : fruit
green : fruit