将字符串转换为数组

时间:2011-03-30 20:45:41

标签: php

我有一个字符串 - 类似于

$string = 'key1=value1, key2=value2, key3=value3';

如何从给定的字符串中获取数组,如下所示?

$array = array(
    'key1' => 'value1',
    'key2' => 'value2',
    'key3' => 'value3',
);

4 个答案:

答案 0 :(得分:8)

parse_str(str_replace(", ","&",$string),$array);

答案 1 :(得分:3)

一个天真的解决方案可能是:

$string = 'key1=value1, key2=value2, key3=value3';

$array = array();
foreach (explode(', ', $string) as $couple) {
    list ($key, $value) = explode('=', $couple);
    $array[$key] = $value;
}

var_dump($array);

结果你得到了预期的数组:

array
  'key1' => string 'value1' (length=6)
  'key2' => string 'value2' (length=6)
  'key3' => string 'value3' (length=6)

答案 2 :(得分:1)

这正是parse_str所做的。在您的情况下,您需要将逗号替换为&

$string = 'key1=value1, key2=value2, key3=value3';
$array = parse_str(str_replace(', ', '&', $string));

// Yields
array(
    'key1' => 'value1',
    'key2' => 'value2',
    'key3' => 'value3',
)

答案 3 :(得分:0)

$a = explode(', ', $string);
$array = array();
foreach($a as $v){
    $x = explode('=', $v);
    $array[$x[0]] = $x[1];
}