PHP 不能在不使用 print_r的情况下打印数组元素


PHP can't print array elements without using print_r

我正在使用一个数据库查询,该查询接收一个州和城市,然后吐出 10 个字段。目前,我只能使用print_r查看这些字段。我尝试了 php 手册站点 a for 循环上的建议来打印字段,但我无法让它正常工作。这是代码:

    if (!$result) {
        echo 'Could not run query: ' . mysql_error();
        exit;
    }
    if (mysql_num_rows($result) > 0) {
        while ($row = mysql_fetch_assoc($result)) {
            print_r($row)."</p>";
            $arrayLength = count($row);
            for ($i = 0; $i < $arrayLength; $i++){
                echo "arrayName at[" . $i . "] is: [" .$row[$i] . "]<br>'n";
            }
                
                
        }
    }

这就是结果:

Array ( [id] => 1299 [zip_code] => 04011 [city] => Brunswick [county] => Cumberland [state_name] => Maine [state_prefix] => ME [area_code] => 207 [time_zone] => Eastern [lat] => 43.9056 [lon] => -69.9646 ) ....
arrayName at[0] is: []
arrayName at[1] is: []
arrayName at[2] is: []
arrayName at[3] is: []
arrayName at[4] is: []
arrayName at[5] is: []
arrayName at[6] is: []
arrayName at[7] is: []
arrayName at[8] is: []
arrayName at[9] is: []

为什么我无法正确打印字段及其值的任何想法?此外,如果查询返回多行,我的代码也会失败,因为当前代码并不能真正容纳它。

我把$i放在 for 循环的主体中,看看它是否正常工作。理想情况下,我会在$i所在的位置使用字段名称,并在冒号后面将其右侧的值放在字段名称中。

你正在用mysql_fetch_assoc所以获取将循环更改为

foreach($row as $key => $value){
echo "Array key : $key = $value <br/>";
}

你的数组键是'id''zip_code'等。数组的01等索引中没有任何内容。

foreach ($row as $key => $value) {
    echo "arrayName at[" . $key . "] is: [" . $value . "]<br>'n";
    // which is the same as:
    echo "arrayName at[" . $key . "] is: [" . $row[$key] . "]<br>'n";
}

是的,因为它返回一个关联数组这意味着您必须访问如下元素:例如$row["id"]

你想要的是这个

foreach($row as $key => $value)
echo "arrayName at[" . $key . "] is: [" .$value . "]<br>'n";

使用 mysql_fetch_array() 而不是 mysql_fetch_assoc()

mysql_fetch_assoc() 将返回一个关联数组,并且只能通过 $row['name'] 访问。使用 mysql_fetch_array(),您可以获取关联数组、数字数组或两者。

看看这里: http://www.php.net/manual/en/function.mysql-fetch-array.php

相关文章: