我有一个关于此代码的问题,我试图弄清楚,因为我是PHP的新手。这是代码:
GeneralJsonRepresentation
如何输出描述每种水果颜色和新量(计数)的字符串?任何帮助将非常感激。谢谢。
答案 0 :(得分:3)
由于所有水果似乎都有颜色,但不一定是数量,只需循环颜色,看看是否有相应水果的数量:
$fruit_counts = array('apple' => 3, 'banana' => 4, 'orange' => 0);
$fruit_colors = array('apple' => 'red', 'banana' => 'yellow', 'orange' => 'orange', 'plum' => 'purple');
foreach ($fruit_colors as $fruit => $color) {
$qty = isset($fruit_counts[$fruit]) ? $fruit_counts[$fruit] : 0;
echo "Fruit: $fruit | Color: $color | Qty: $qty" . '<br>';
}
答案 1 :(得分:2)
如果您想要所有水果计数,请使用相关颜色:
$fruit_counts=array('apple'=>3, 'banana'=>4, 'orange'=>0);
$fruit_colors=array('apple'=>'red', 'banana'=>'yellow', 'orange'=>'orange', 'plum'=>'purple');
foreach($fruit_counts as $Fruit=>$Count){
$Colour = "None!";
if(isset($fruit_colors[$Fruit])){
$Colour = $fruit_colors[$Fruit];
}
echo "<p>$Fruit ($Colour): $Count</p>";
}
或者,如果您想要所有水果颜色,并且具有关联计数:
foreach($fruit_colors as $Fruit=>$Colour){
$QTY = 0;
if(isset($fruit_counts[$Fruit])){
$QTY = $fruit_counts[$Fruit];
}
echo "<p>$Fruit ($Colour): $QTY</p>";
}
答案 2 :(得分:-1)
$fruit_colors=array('apple'=>'red', 'banana'=>'yellow', 'orange'=>'orange', 'plum'=>'purple');
$fruit_counts=array('apple'=>3, 'banana'=>4, 'orange'=>0);
foreach($fruit_colors as $key=>$color){
if($fruit_counts[$key]){
echo "Color :".$key." Count: ".$fruit_counts[$key];
}
}