简体   繁体   English

PHP数组-如何遍历数组

[英]PHP Array - How to loop through an array

My array is as follows: 我的数组如下:

Array ( [questions] => 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. 如果有人可以提供PHP和HTML代码,那就太好了,谢谢。

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. 我也想只访问[qtext]元素。

Is this possible? 这可能吗?

Homer. 荷马

You can use the foreach construct here. 您可以在此处使用foreach构造。

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 您可以像这样使用foreach

$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>';
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM