数组中的单独值多于一个(内爆)

时间:2016-12-07 02:55:28

标签: php arrays implode

假设我有一个字符串:

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

我想像这样存储它:

type[] => fruit,vegetable

item[] => apple,orange,carrot

任何人都可以帮我吗?

3 个答案:

答案 0 :(得分:1)

此代码会将其放在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

答案 1 :(得分:1)

这是一个将您的字符串解析为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单字符串,你可以像这样使用join:

print join(',',$type);

答案 2 :(得分:0)

尝试这样的事情:

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

应该返回这样的内容:

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
        )

)