Double爆炸数组

时间:2013-05-15 23:21:11

标签: php arrays explode

字符串:

user:hello,user2:world

期望的输出:

$string = array(
   1 => array( 1 => "user", 2 => "hello"),
   2 => array( 1 => "user2", 2 => "world")
);

我尝试过的(不起作用):

$string = explode(',',$string);
$string = explode(':',$string);

我得到的错误:explode() expects parameter 2 to be string
如何从字符串到所需的输出?谢谢!

4 个答案:

答案 0 :(得分:5)

循环第一次爆炸的输出,并在每个值上第二次爆炸。

$string = "user:hello,user2:world";
$array = explode(',', $string);

foreach($array as $k=>$v){
    $array[$k] = explode(':', $v);
}

答案 1 :(得分:3)

请试试这个:

$string = 'user:hello,user2:world';
$output = explode(',',$string);
foreach ($output as &$e) {
    $e = explode(':', $e);
}
print_r($output);

答案 2 :(得分:2)

<?php

$string = "user:hello,user2:world";

$array = array_map(function ($input) {
    return explode(':',$input);
}, explode(',', $string));

print_r($array);

答案 3 :(得分:0)

您可以使用example of user from manual

function multiexplode ($delimiters,$string) {
    $ary = explode($delimiters[0],$string);
    array_shift($delimiters);
    if($delimiters != NULL) {
        foreach($ary as $key => $val) {
             $ary[$key] = multiexplode($delimiters, $val);
        }
    }
    return  $ary;
}

// Example of use
$string = "1-2-3|4-5|6:7-8-9-0|1,2:3-4|5";
$delimiters = Array(",",":","|","-");

$res = multiexplode($delimiters,$string);
echo '<pre>';
print_r($res);
echo '</pre>';