PHP爆炸数组然后遍历值并输出到变量 [英] PHP explode array then loop through values and output to variable

查看:42
本文介绍了PHP爆炸数组然后遍历值并输出到变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图拆分的字符串是 $item['category_names'] 例如包含 Hair, Fashion, News

The string I am trying to split is $item['category_names'] which for example contains Hair, Fashion, News

我目前有以下代码:

$cats = explode(", ", $item['category_names']);
foreach($cats as $cat) {
    $categories = "<category>" . $cat . "</category>\n";
}

我希望 $categories 的结果如下所示,以便我可以稍后在某处回显.

I want the outcome of $categories to be like the following so I can echo it out later somewhere.

<category>Hair</category>\n
<category>Fashion</category>\n
<category>News</category>\n

不确定我的做法是否正确?

Not sure if I am going the right way about this?

推荐答案

在您的代码中,您将在每次迭代中覆盖 $categories 变量.正确的代码如下所示:

In your code you are overwritting the $categories variable in each iteration. The correct code would look like:

$categories = '';
$cats = explode(",", $item['category_names']);
foreach($cats as $cat) {
    $cat = trim($cat);
    $categories .= "<category>" . $cat . "</category>\n";
}

更新:正如@Nanne 建议的那样,只在,"上爆炸

update: as @Nanne suggested, explode only on ','

这篇关于PHP爆炸数组然后遍历值并输出到变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆