php foreach echo prints "Array" as value 问这个问题但不是这里的情况
try {require_once'libs/config.php';
$con = new PDO($dsn, $user, $pass, $opt);
$query = "SELECT * FROM table ";
//first pass just gets the column names
print "<table> \n";
$result = $con->query($query);
//return only the first row (we only need field names)
$row = $result->fetch(PDO::FETCH_ASSOC);
print "<thead> <tr> \n";
foreach ($row as $field => $value){
print " <th>$field</th> \n";
} // end foreach
print " </tr> </thead> <tbobdy> \n";
//second query gets the data
$data = $con->query($query);
$data->setFetchMode(PDO::FETCH_ASSOC);
foreach($data as $row){
echo $ row; //打印阵列阵列阵列阵列阵列阵列阵列阵列阵列阵列阵列阵列阵列阵列阵列阵列阵列阵列阵列阵列阵列阵列阵列阵列阵列阵列阵列阵列阵列阵列阵列阵列阵列阵列阵列阵列阵列阵列阵列阵列阵列阵列阵列阵列阵列阵列阵列阵列阵列阵列阵列阵列
print " <tr> \n";
foreach ($row as $name=>$value){
print "<td>$value</td>\n"; }
} // end field loop
print " </tr> \n";
} // end record loop
// print "</tbody> </table> \n";
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
} // end try
$con = null;
?>
答案 0 :(得分:1)
这么简单就意味着$ row是一个数组而不是一个变量。您需要print_r($row);
而不是echo $row;
答案 1 :(得分:0)
您需要在$value
循环中打印foreach
,因为它包含数组元素的值。
你的最终输出将是这样的:
<?php
try {
require_once 'libs/config.php';
$con = new PDO($dsn, $user, $pass, $opt);
$query = "SELECT * FROM table ";
//first pass just gets the column names
print "<table> \n";
$result = $con->query($query);
//return only the first row (we only need field names)
$row = $result->fetch(PDO::FETCH_ASSOC);
print "<thead> <tr> \n";
foreach ($row as $field => $value) {
print " <th>$value</th> \n";
} // end foreach
print " </tr> </thead> <tbobdy> \n";
//second query gets the data
$data = $con->query($query);
$data->setFetchMode(PDO::FETCH_ASSOC);
foreach ($data as $Somefield => $SomeValue) {
echo $SomeValue; // prints your disered output
print " <tr> \n";
foreach ($row as $name => $value) {
print "<td>$value</td>\n";
}
} // end field loop
print " </tr> \n";
} // end record loop
// print "</tbody> </table> \n";
catch (PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
} // end try
$con = null;
?>
?>
答案 2 :(得分:0)
我认为我得到它foreach as ..
无法回显一个完整的数组,无论是键还是值,或两者都有,如果它是一个阵列,它打印出来的阵列&#39;因为$ data包含一个数组,它只是打印出来的整行&#39; array&#39;,
每个多维数组都是如此,你可以从php docs
/* foreach example 4: multi-dimensional arrays */
$a = array();
$a[0][0] = "a";
$a[0][1] = "b";
$a[1][0] = "y";
$a[1][1] = "z";
foreach ($a as $v1) {
foreach ($v1 as $v2) {
echo "$v2\n";
}
}
数据库的结果是一个多维数组