开发者

PHP Array - How to loop through an array

My array is as follows:

Array ( [question开发者_开发问答s] => q1 [qnum] => 1 [qtext] => I love crisps [page] => 1 )
Array ( [questions] => q2 [qnum] => 2 [qtext] => I love chocolate [page] => 1 )

All I would like to do is print the contents of the array in a loop, so it looks something like:

q1 1 I love crisps
q2 2 I love chocolate

If anyone could supply the PHP and HTML code, that would be great, thanks.

This is a multi-dimensional array - I should have stated that. In addition, I want to be able to access each element of the array row, for example. I also want to just access the [qtext] element on its own.

Is this possible?

Homer.


You can use the foreach construct here.

foreach($arr as $value)
{
    echo "$value ";
}

If you wanted to print out the keys too you could use:

foreach($arr as $key => $value)
{
    echo "$key: $value ";
}

And if you just want to print out for debugging there's always

print_r($arr);


You can use foreach like so

$arr = array("foo" => "bar", 12 => true);

foreach ($arr as $key => $value)
{
echo "$key => $value<br />\n";
}


If it's just an array of arrays, you would do something like this:

foreach ($multi_array as $arr)
{
    foreach($arr as $item)
    {
        echo $item['questions'], ' ', $item['qnum'], ' ', $item['qtext'], '<br>';
    }
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜