我有一个字符串
$string = 'S:1,M:1,L:1,XL:1,XXL:1,3XL:1';
我想创建一个
的数组$array['S'] = 1;
$array['M'] = 1;
我以为我可以爆炸(',',$ string); 然后爆炸(':',$ string);再次;-) 但这根本不起作用。
答案 0 :(得分: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);
拆分它,遍历拆分,然后将它们作为键值对插入到结果数组中。
答案 1 :(得分:2)
是的,您可以explode()
两次,但第二个必须处于循环中:
$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 :(得分:0)
试试这个:
$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);
希望这会有所帮助:)