简体   繁体   English

如何在echo中使用foreach来回显数组

[英]how to echo array using foreach in echo

I have an array $category_slugs 我有一个数组$category_slugs

how to output this using echo ? 如何使用echo输出呢?

I have an error in code bellow: 我在下面的代码中有一个错误:

echo "<div class='transition ".foreach($category_slugs as $slug){echo $slug;echo ' ';}."' data-category='transition'> " ?>

Thanks 谢谢

You can't use foreach inside a echo . 您不能在echo使用foreach。 To achieve what you are trying you can use implode function, it concatenates the values of an array on a string. 要实现您要尝试的功能,可以使用内implode函数,它将字符串数组的值连接在一起。

echo "<div class='transition " .implode(' ', $category_slugs). "' data-category='transition'> " ?>

try this code 试试这个代码

<div class="transition <?php foreach($category_slugs as $slug){echo $slug . ' ';} ?>" data-category="transition">

The concatenation operator ('.'), which returns the concatenation of its right and left arguments. 串联运算符('。'),返回其左右参数的串联。

from php manual PHP手册

But this code not a string. 但是这段代码不是字符串。

foreach($category_slugs as $slug){echo $slug;echo ' ';}

So you will get a error. 所以你会得到一个错误。

This manual may help you Escaping from HTML . 本手册可以帮助您逃脱HTML的困扰

Sorry for my bad english, I hope it will help you. 对不起,我的英语不好,希望对您有帮助。

Wrap <div> in a for loop, like so <div>包装在for循环中,如下所示

<?php

$slug_string = "";

foreach($category_slugs as $slug){

$slug_string .= $slug_string." ";

}

echo "<div class='transition ".$slug_string."' data-category='transition'> ";

?>

try this 尝试这个

$category_slugs =array('a','b','c');
foreach($category_slugs as $slug){
echo "<div class='transition ".$slug.' '."' data-category='transition'></div> " ;
}

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

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