Multi Dem php string to array - comma separated, colon separated array

你说的曾经没有我的故事 提交于 2019-12-08 06:22:11

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!