2

字符串:

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

4 回答 4

6

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

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

foreach($array as $k=>$v){
    $array[$k] = explode(':', $v);
}
于 2013-05-15T23:28:12.533 回答
4
<?php

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

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

print_r($array);
于 2013-05-15T23:56:46.297 回答
3

请试试这个:

$string = 'user:hello,user2:world';
$output = explode(',',$string);
foreach ($output as &$e) {
    $e = explode(':', $e);
}
print_r($output);
于 2013-05-15T23:31:20.573 回答
0

您可以使用手册中的用户示例

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>';
于 2013-05-15T23:27:58.713 回答