Php 打印从SQL数据库获取的关联数组
我从数据库中提取了3个数组,并将它们放入关联数组中 我已经学会了打印数组,如下面的注释所示,但这似乎不起作用?我怎样才能做到这一点Php 打印从SQL数据库获取的关联数组,php,mysql,arrays,Php,Mysql,Arrays,我从数据库中提取了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); //ca
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
}
而是这样:
$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
}
而是这样:
$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
}
这是一个奇怪的数组,我会简化它,但是使用
$key
和名称($value
)来访问其他数组:
echo "$value is of gender {$arrGender[$key][$value]}
and has a bmi of {$arrBmi[$key][$value]}";
要保持简单,只需使用从获取中获取的数组:
$array[] = ['name' => $row['name'],
'gender' => $row['gender'],
'bmi' => $bmi];
然后在循环中:
echo "{$value['name']} is of gender {$value['gender']}
and has a bmi of {$value['bmi']}";
这是一个奇怪的数组,我会简化它,但是使用
$key
和名称($value
)来访问其他数组:
echo "$value is of gender {$arrGender[$key][$value]}
and has a bmi of {$arrBmi[$key][$value]}";
要保持简单,只需使用从获取中获取的数组:
$array[] = ['name' => $row['name'],
'gender' => $row['gender'],
'bmi' => $bmi];
然后在循环中:
echo "{$value['name']} is of gender {$value['gender']}
and has a bmi of {$value['bmi']}";
不要使用不推荐使用且不安全的
mysql.*
-函数。自PHP5.5(2013年)起,它们就被弃用,并在PHP7(2015年)中被完全删除。改用MySQLi或PDO。错误:数组到字符串conversion@MagnusEriksson你能给我指出一个等价的函数吗?哦,是数组的数组<代码>{$arrGender[$key][$value]}。您也可以执行BMI
,然后迭代每个$row
的值。您放弃了吗?不要使用不推荐使用且不安全的mysql.*
-函数。自PHP5.5(2013年)起,它们就被弃用,并在PHP7(2015年)中被完全删除。改用MySQLi或PDO。错误:数组到字符串conversion@MagnusEriksson你能给我指出一个等价的函数吗?哦,是数组的数组<代码>{$arrGender[$key][$value]}。你也可以做BMI
,然后迭代每个$row
的值。你放弃了吗?