PHP explode array then loop through values and output to variable

后端 未结 5 580
眼角桃花
眼角桃花 2020-12-15 11:07

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

I currently have the following

相关标签:
5条回答
  • 2020-12-15 11:21

    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";
    
    0 讨论(0)
  • 2020-12-15 11:30

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

    0 讨论(0)
  • 2020-12-15 11:35

    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 ' ';
    
    }
    }
    ?>
    
    0 讨论(0)
  • 2020-12-15 11:36

    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 :)

    0 讨论(0)
  • 2020-12-15 11:41

    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;
    
    0 讨论(0)
提交回复
热议问题