PHP explode array then loop through values and output to variable

后端 未结 5 585
眼角桃花
眼角桃花 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条回答
  •  Happy的楠姐
    2020-12-15 11:21

    The error in your code is this:

    $categories = "" . $cat . "\n";
    

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

    $categories .= "" . $cat . "\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 = "" .
        str_replace(', ', "\n", $input) . 
        "\n";
    

    And this also accounts for variable whitespace:

    $categories = "" . 
        preg_replace('@\s*,\s*@', "\n", $input) . 
        "\n";
    

提交回复
热议问题