问题
I have a string
$string = 'S:1,M:1,L:1,XL:1,XXL:1,3XL:1';
I want to create an array where
$array['S'] = 1;
$array['M'] = 1;
I thought i could explode(',', $string); and then explode(':', $string); again ;-) but that doesn't work at all.
回答1:
Yes, you can explode() twice, but the second one has to be in a loop:
$string = 'S:1,M:1,L:1,XL:1,XXL:1,3XL:1';
// Split on the commas
$sizes = explode(",", $string);
// Output array
$quantities = array();
// Loop over the first explode() result
foreach ($sizes as $size) {
// Assign each pair to $s, $q
list($s, $q) = explode(":", $size);
// And put them onto an array keyed by size
$quantities[$s] = $q;
}
// This builds an array like:
Array
(
[S] => 1
[M] => 1
[L] => 1
[XL] => 1
[XXL] => 1
[3XL] => 1
)
回答2:
$string = 'S:1,M:1,L:1,XL:1,XXL:1,3XL:1';
$result = array();
foreach (explode(',',$string) as $sub){
$subAry = explode(':',$sub)
$result[$subAry[0]] = $subAry[1];
}
var_dump($result);
Split it, iterate over the splits, then insert them in to resulting array as a key-value pair.
回答3:
Try this:
$str = 'S:1,M:1,L:1,XL:1,XXL:1,3XL:1';
$tokens = explode(',', $str);
$sizes = array();
foreach ($tokens as $el) {
list($k, $v) = explode(':', $el);
$sizes[$k] = $v;
}
print_r($sizes);
Hope this helps :)
来源:https://stackoverflow.com/questions/9855239/multi-dem-php-string-to-array-comma-separated-colon-separated-array