[英]PHP For Loop Printing An Array
This might seem like a really easy question but it has got me stumped lol. 这似乎是一个非常简单的问题,但这让我很困惑。 I am trying to print the rows received from the database.
我正在尝试打印从数据库接收的行。 I want to store the rows inside an array and then print them using a for loop.
我想将行存储在数组中,然后使用for循环打印它们。 I know that the query works however when I try to print the array elements it only prints the word array.
我知道查询有效,但是当我尝试打印数组元素时,它仅打印单词数组。 I have tired doing it with a foreach loop and a simple for loop.
我已经厌倦了使用foreach循环和简单的for循环来做到这一点。 If anyone can point me in the right direction would be a life saver.
如果有人能指出正确的方向,那将是救生员。
Printing Php Code 打印PHP代码
<?php
$type = "FREE";
$free = getTerms($type);
echo "<p>";
for($j = 0; $j < count($free); $j++)
{
echo "start".$free[$j]."end";
}
echo "</p>";
?>
geting the rows from the database 从数据库中获取行
function getTerms($type)
{
$terms = array();
$connection = mysql_open();
$query = "select terms from terms_and_con where accountType='$type' && currentTerms='YES'";
$results = mysql_query($query, $connection) or show_error("signUp.php", "", "");
while($row = mysql_fetch_array($results))
{
$terms[] = $row;
}
mysql_close($connection) or show_error("signUp.php", "", "");
return $terms;
}
Each entry in the $free
array is itself an array (from $row
). $free
数组中的每个条目本身都是一个数组(来自$row
)。
Try 尝试
echo 'start', $free[$j]['terms'], 'end';
Alternatively, you may find a foreach
loop more semantically appropriate 另外,您可能会发现
foreach
循环在语义上更合适
foreach ($free as $row) {
echo 'start', $row['terms'], 'end';
}
Edit: I'd advise using mysql_fetch_assoc()
instead of mysql_fetch_array()
if you're only going to use associative entries from $row
. 编辑:如果您只打算使用
$row
关联条目,建议使用mysql_fetch_assoc()
而不是mysql_fetch_array()
。
the thing is function mysql_fetch_array ( as the name suggests) returns an ( in your case both associative and number) array. 事情是函数mysql_fetch_array(顾名思义)返回一个(在您的情况下为关联和数字)数组。 so $row is actually array(0 => VALUE , 'terms' => ' VALUE ')
所以$ row实际上是array(0 => VALUE ,'terms'=>' VALUE ')
So what you are trying to echo is actually an array. 因此,您要回显的实际上是一个数组。
Simple fix: replace: 简单修复:替换:
$terms[] = $row;
with: 与:
$terms[] = $row[0];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.