php 如何在php中使用foreach()回显数组数据?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12751875/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 04:09:20  来源:igfitidea点击:

How to echo array data using foreach() in php?

phpforeach

提问by ehp

I have an array like the one below given. I want to echo this elements one by one. Expected output also added with the post

我有一个像下面给出的数组。我想一一呼应这个元素。预期输出也随帖子添加

$myArray => Array
        (
            [0] => Array
                (
                    ['id'] => 1
                    ['name'] => "Amla"
                    ['age'] => 25
                )

            [1] => Array
                (
                    ['id'] => 2
                    ['name'] => "Kallis"
                    ['age'] => 35
            )
       )

// expected output

// 预期输出

1  Amla  25
2  Kallis 35

My code:

我的代码:

foreach ($myArray as $key => $value){
    echo "$myArray[$key]=>$value"."</br>";
    }

回答by Rooster

Simple approach. Add css to the spans if you want.

简单的方法。如果需要,将 css 添加到跨度。

 foreach($my_array as $item):
      echo '<span>'.$item['id'].'</span>';
      echo '<span>'.$item['name'].'</span>';
      echo '<span>'.$item['age'].';</span>';
 endforeach;

回答by Database_Query

try

尝试

foreach ($myArray  as $v1) {
    foreach ($v1 as $v2) {
        echo "$v2\n";
    }
}

回答by dan

The easiest way:

最简单的方法:

<?php
    foreach($my_array as $item) {
        echo $item['id'], " ", $item['name'], " ", $item['age'];
    }
?>

You can edit the format of the output with CSS. Please note that I use commas instead of dots for the echo(): it's faster to call the function multiple times than concatenate.

您可以使用 CSS 编辑输出的格式。请注意,我对 使用逗号而不是点echo():多次调用函数比连接更快。

Sources:

资料来源:

http://wolfprojects.altervista.org/articles/output-in-php/

http://wolfprojects.altervista.org/articles/output-in-php/

http://www.simplemachines.org/community/index.php?topic=27423.0

http://www.simplemachines.org/community/index.php?topic=27423.0