问题
The string:
user:hello,user2:world
Desired Output:
$string = array(
1 => array( 1 => "user", 2 => "hello"),
2 => array( 1 => "user2", 2 => "world")
);
What I've tried (that doesn't work):
$string = explode(',',$string);
$string = explode(':',$string);
The error I get: explode() expects parameter 2 to be string
How can I get from the string to the desired output? Thanks!
回答1:
loop over the output from the first explode and explode the second time on each value.
$string = "user:hello,user2:world";
$array = explode(',', $string);
foreach($array as $k=>$v){
$array[$k] = explode(':', $v);
}
回答2:
Please try this:
$string = 'user:hello,user2:world';
$output = explode(',',$string);
foreach ($output as &$e) {
$e = explode(':', $e);
}
print_r($output);
回答3:
<?php
$string = "user:hello,user2:world";
$array = array_map(function ($input) {
return explode(':',$input);
}, explode(',', $string));
print_r($array);
回答4:
You can use 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>';
来源:https://stackoverflow.com/questions/16576545/double-explode-an-array