<?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
数组的一点乐趣:
$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";
}
您可以通过修改第一行轻松地将其扩展到任意数量的数组。
因此,您似乎对获取各种对象的颜色感兴趣,并切换关联以使颜色反映对象,而不是相反。
这是一种适用于您的场景的方法:
<?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