我从数据库中取出3个数组并将它们放在关联数组中。
我已经学会了在评论中打印出如下所示的数组,但这似乎不起作用?我怎样才能做到这一点?
while($row = mysql_fetch_array($query)) //fetching row in db
{
$weight = $row['weight'];
$height = $row['height'];
$bmi = round($weight / (pow(($height/100),2)),2); //calculates bmi
$arrName[] = $row['name']; //main name array
$arrGender[] = array($row['name'] => $row['gender']); //this and below are associative arrays
$arrBmi[] = array($row['name'] => $bmi);
}
foreach($arrName as $key=>$value){
echo "$value is of gender {$arrGender[$value]} and has a bmi of {$arrBmi[$value]}"; //this line
}
答案 0 :(得分:2)
改为:
$arrGender[$row['name']] = $row['gender']
$arrBmi[$row['name']] = $bmi);
您正在这样做,您将多个子数组分配给数字索引,而不是使用名称作为键。如果最终以这种方式执行此操作,需要注意的一点是,如果查询结果中存在非唯一名称,则该数组键的值将被覆盖以用于后续重复名称。
但是看起来你真的不需要第二个循环。在获取结果时,您可以在while循环中输出相同的内容:
while ($row = mysql_fetch_array($query)) //fetching row in db
{
$bmi = round( $row['weight'] / (pow(( $row['height'] /100),2)),2); //calculates bmi
echo "$row[name] is of gender $row[gender] and has a bmi of $bmi"; //this line
}
答案 1 :(得分:1)
这是一个奇怪的数组,我会简化它,但使用$key
和名称($value
)来访问其他人:
echo "$value is of gender {$arrGender[$key][$value]}
and has a bmi of {$arrBmi[$key][$value]}";
为了简单起见,只需使用数组,因为它来自fetch:
$array[] = ['name' => $row['name'],
'gender' => $row['gender'],
'bmi' => $bmi];
然后在循环中:
echo "{$value['name']} is of gender {$value['gender']}
and has a bmi of {$value['bmi']}";