PHP explode array then loop through values and out

2020-02-09 17:48发布

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

I currently have the following code:

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

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?

标签: php arrays
5条回答
叛逆
2楼-- · 2020-02-09 18:25

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";
}

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

查看更多
Explosion°爆炸
3楼-- · 2020-02-09 18:42

The error in your code is this:

$categories = "<category>" . $cat . "</category>\n";

You are overwriting $categories at each iteration, it should be:

$categories .= "<category>" . $cat . "</category>\n";

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

find and replace isn't what explode is for. If you just want to correct the code error - see above.

This is more efficient:

$categories = "<category>" .
    str_replace(', ', "</category>\n<category>", $input) . 
    "</category>\n";

And this also accounts for variable whitespace:

$categories = "<category>" . 
    preg_replace('@\s*,\s*@', "</category>\n<category>", $input) . 
    "</category>\n";
查看更多
走好不送
4楼-- · 2020-02-09 18:44

Without a for loop

$item['category_names'] = "Hair,   Fashion,   News";
$categories = "<category>".
        implode("</category>\n<category>", 
        array_map('trim', explode(",", $item['category_names']))) . 
        "</category>\n";
echo $categories;
查看更多
啃猪蹄的小仙女
5楼-- · 2020-02-09 18:46

if you use this:

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

the $categories string is overwritten each time, so "hair" and "fasion" are lost..

if you however add a dot before the equal sign in the for loop, like so:

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

the $catergories string will consist of all three values :)

查看更多
闹够了就滚
6楼-- · 2020-02-09 18:50

PHP explode array by loop demo: http://sandbox.onlinephpfunctions.com/code/086402c33678fe20c4fbae6f2f5c18e77cb3fbc2

its works for me

<?php

$str = "name:john,hone:12345,ebsite:www.23.com";

$array=explode(",",$str);

if(count($array)!=0)
{
foreach($array as $value)
{

    $data=explode(":",$value);

      echo $data[0]."=".$data[1];


    echo ' ';

}
}
?>
查看更多
登录 后发表回答