多Dem php字符串到数组-逗号分隔,冒号分隔的数组 [英] Multi Dem php string to array - comma separated, colon separated array
本文介绍了多Dem php字符串到数组-逗号分隔,冒号分隔的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个字符串
$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;
我以为我会爆炸(’,’,$ string);
然后爆炸(’:’,$ string);再次;-)
,但这根本不起作用。
I thought i could explode(',', $string); and then explode(':', $string); again ;-) but that doesn't work at all.
推荐答案
是的,您可以 explode()
两次,但是第二个必须循环:
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
)
这篇关于多Dem php字符串到数组-逗号分隔,冒号分隔的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文