在以下代码中,结果包含几个产品,且每个产品都有几列:
$db = connect_db();
$sql = "SELECT * FROM Products";
$result = $db->query($sql);
$ary = $result->fetch_array(MYSQLI_ASSOC);
foreach($ary as $key => $element){
echo "key is $key, element is $element \n";
}但输出仅迭代单个产品的每一列:
key is id, element is 1
key is productCode, element is S10_1678
key is productName, element is 1969 Harley Davidson Ultimate Chopper
key is productLineId, element is 5
key is productScale, element is 1:10
key is productVendor, element is Min Lin Diecast
key is productDescription, element is This replica features working kickstand, front suspension, gear-shift lever, footbrake lever, drive chain, wheels and steering. All parts are particularly delicate due to their precise scale and require special care and attention.
key is quantityInStock, element is 7933
key is buyPrice, element is 48.81
key is MSRP, element is 95.7如何获取$array[0]['MSRP']对95.7求值的二维数组
发布于 2012-08-19 21:56:14
我相信这将会奏效:
while ($ary = $result->fetch_array(MYSQL_ASSOC){
foreach($ary as $key => $element){
echo "key is $key, element is $element \n";
}
}这意味着当有更多的记录时,它会将它们放入数组并打印出来。这是基于旧的mysql_fetch_assoc()和mysql_fetch_array()。
祝好运。
如果你想实现你想要的东西,你只需要做以下几件事:
while ($ary = $result->fetch_array(MYSQL_ASSOC){
foreach($ary){
$array[] = $ary;
}
}现在$array有了整个结果集,因此$array[0]['MSRP'] -将返回您想要的值。
发布于 2012-08-19 21:55:56
$ary = $result->fetch_array(MYSQLI_ASSOC)一次只获取一条记录,这是本例中的第一条记录,您将需要使用while
while($ary = $result->fetch_array(MYSQLI_ASSOC)) //fetching one record at a time until end of record
{
foreach($ary as $key => $element){
echo "key is $key, element is $element \n";
}
}发布于 2012-08-19 21:58:43
您需要迭代mysql_fetch命令,而不是该命令的结果。
例如:
$db = connect_db();
$sql = "SELECT * FROM Products";
$result = $db->query($sql);
while($entry = mysql_fetch_assoc($result))
{
// $entry is an array you with the data of this DB-entry, eg
echo $entry['MSRP'];
}https://stackoverflow.com/questions/12026979
复制相似问题