数组中的多个值分开(内爆)

Separate value in array more than one (implode)

假设我有一个字符串:

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

我想这样存储它:

type[] => fruit,vegetable

item[] => apple,orange,carrot

谁能帮我解决这个问题?

此代码将把它放在 array 中,这样您就可以轻松访问它,see DEMO

<?php
$string = "fruit: apple,fruit: orange,vegetable: carrot";
$output = array(array());
foreach(explode(",", $string) as $item){
    $parts = explode(": ",trim($item));
    if(array_key_exists($parts[0], $output)){
        array_push($output[$parts[0]], $parts[1]);
    }else{
        $output[$parts[0]] = array($parts[1]);
    }
}
?> 

它会给你一个 array 这样的结果

<?php
$output = array(
    "fruit" => array(
        "apple",
        "orange"
        ),
    "vegetable" => array(
        "carrot"
        )
    );
?>

要稍后获取该信息,您可以这样做:

$output["fruit"][0];

这将为您提供以下结果:apple 在这种情况下。

这里有一段代码可以将您的字符串解析为 2 个数组。

<?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);

如果您希望 $type 像您的问题一样成为 CSV 单个字符串,您可以像这样使用连接:

print join(',',$type);

尝试这样的事情:

$string = "fruit: apple, fruit: orange, vegetable: carrot,";
preg_match_all("/([a-zA-Z0-9]*): ([a-zA-Z0-9]*),/U", $string, $output_array);
print_r($output_array);

应该return像这样:

Array
(
    [0] => Array
        (
            [0] => fruit: apple,
            [1] => fruit: orange,
            [2] => vegetable: carrot,
        )

    [1] => Array
        (
            [0] => fruit
            [1] => fruit
            [2] => vegetable
        )

    [2] => Array
        (
            [0] => apple
            [1] => orange
            [2] => carrot
        )

)