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){回波$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;
?>发布于 2015-03-25 13:46:04
这意味着$row是一个数组,而不是变量。你需要做print_r($row);而不是echo $row;
发布于 2015-03-25 05:41:21
您需要在$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;
?>
?>发布于 2015-03-25 13:34:53
我想我得到它了,foreach as ..不能回显一个完整的数组(它的键或值,或者两者兼而有之),如果它是一个数组,它会在这里打印一个‘数组’,因为$data包含一个数组,它只打印‘数组’,这对于每个多维数组都是正确的,因为您可以从php文档中看到下面的示例。
/* 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";
}
}数据库的结果是多维数组。
https://stackoverflow.com/questions/29248224
复制相似问题