PHP explodes the array, then iterates over the values ​​and outputs the variable

The line I'm trying to split $item['category_names'], which contains, for example,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 result to $categoriesbe as follows: so that I can repeat it later.

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

Not sure if I will return right?

+5
source share
4 answers

In your code, you replace the $ categories variable at each iteration. The correct code would look like this:

$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 ','

+13
source

No loop cycle

$item['category_names'] = "Hair,   Fashion,   News";
$categories = "<category>".
        implode("</category>\n<category>", 
        array_map('trim', explode(",", $item['category_names']))) . 
        "</category>\n";
echo $categories;
+2
source

:

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

$categories , "" "fasion" .

, , for, :

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

$catergories :)

0
source

Error in your code:

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

You rewrite $categoriesat each iteration, it should be:

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

Not sure if I will be back on this?

Find and replace is not for what an explosion is needed. If you just want to fix a code error - see above.

It is more efficient:

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

And this also takes into account variable spaces:

$categories = "<category>" . 
    preg_replace('@\s*,\s*@', "</category>\n<category>", $input) . 
    "</category>\n";
0
source

All Articles