将带有 2 个分隔符的字符串转换为平面关联数组

问题描述 投票:0回答:1

这是一个字符串..

$string = "foo1 : bar1, foo2: bar2, foo3: bar3"; 

使用

,
定界仪

进行爆炸
$exploded = (",", $string);

现在

$exploded
数组包含:

foo1 : bar1

foo2 : bar2

foo3 : bar3

现在我需要将

foo1
放入
array['key']
并将
bar1
放入
array['value']

如何实现这一目标?

php arrays explode text-parsing
1个回答
3
投票

您需要创建另一个循环来遍历

"foo:bar"
字符串数组并分解它们:

$exploded = explode(",", $input);  
$output = array();       //Array to put the results in
foreach($exploded as $item) {  //Go through "fooX : barX" pairs
  $item = explode(" : ", $item); //create ["fooX", "barX"]
  $output[$item[0]] = $item[1];  //$output["fooX"] = "barX";
}
print_R($output);

请注意,如果相同的键在输入字符串中出现多次 - 它们将相互覆盖,并且结果中仅存在最后一个值。

© www.soinside.com 2019 - 2024. All rights reserved.