[英]How to convert a string that contains an associative array to an associative array type?
I have a string that contains associative array like that 我有一个包含这样的关联数组的字符串
$string = "['key1'=>'value1','key2'=>'value2','key3'=>'value3']";
and I want to convert it to an associative array so i can loop through it. 我想将其转换为关联数组,以便我可以遍历它。
is there any way to do it ? 有什么办法吗?
Thanks in advance . 提前致谢 。
You can use preg_match_all
Like so: 您可以像这样使用
preg_match_all
:
$string = "['key1'=>'value1','key2'=>'value2','key3'=>'value3']";
preg_match_all("/'(?P<key>[-\w]+)'\s*=\>\s*'(?P<value>[-\w]+)'/", $string, $matches);
print_r($matches);
Output: 输出:
Array
(
[0] => Array
(
[0] => 'key1'=>'value1'
[1] => 'key2'=>'value2'
[2] => 'key3'=>'value3'
)
[key] => Array
(
[0] => key1
[1] => key2
[2] => key3
)
[1] => Array
(
[0] => key1
[1] => key2
[2] => key3
)
[value] => Array
(
[0] => value1
[1] => value2
[2] => value3
)
[2] => Array
(
[0] => value1
[1] => value2
[2] => value3
)
)
One note is that [-\\w]+
matchs az
, AZ
, 0-9
, -
and _
, so this should be the format for both the keys and values. 需要注意的是
[-\\w]+
匹配az
, AZ
, 0-9
, -
和_
,因此这应该是键和值的格式。 You can of course adjust the Regx to your needs. 您当然可以根据需要调整Regx。
Now if you want to put them in a more usable format you can add this: 现在,如果您想将它们以更实用的格式放置,可以添加以下内容:
$output = array_combine($matches['key'],$matches['value']);
Output 产量
Array
(
[key1] => value1
[key2] => value2
[key3] => value3
)
One note I should say, is this will not work for nested arrays, for that you need something a bit more advanced. 我应该指出的一点是,这不适用于嵌套数组,因为您需要更高级的东西。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.