Search code examples
phparraysimplode

Separate value in array more than one (implode)


Let say i have a string:

"fruit: apple, fruit: orange, vegetable: carrot,"

i would like to to store it like this:

type[] => fruit,vegetable

item[] => apple,orange,carrot

can anyone help me on this?


Solution

  • here is a code that will parse your string into 2 arrays.

    <?php
    $type=array();
    $item=array();
    $a="fruit: apple, fruit: orange, vegetable: carrot,";
    foreach (explode(',',trim($a,',')) as $csv){
        list($k,$v)=explode(':',$csv);
        $k=trim($k);
        $v=trim($v);
        if($k && $v){
            if(!in_array($k,$type)) $type[]=$k;
            if(!in_array($v,$item)) $item[]=$v;
        }
    }
    print_r($type);
    print_r($item);
    

    if you want the $type to be a CSV single string like in your question, you can use join like this:

    print join(',',$type);