开发者

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. 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. If anyone can point me in the right direction would be a life saver.

Printing Php Code

<?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='$ty开发者_如何学编程pe' && 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).

Try

echo 'start', $free[$j]['terms'], 'end';

Alternatively, you may find a foreach loop more semantically appropriate

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.


the thing is function mysql_fetch_array ( as the name suggests) returns an ( in your case both associative and number) array. so $row is actually 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];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜