[英]PHP: Parse string [“key”, “value”] into associative array
How can I parse a string of the following format into an associative array? 如何将以下格式的字符串解析为关联数组?
[ ["key1", "value1"], ["key2", "value2"], ["key3", "value3] ]
Into: 进入:
Array
(
["key1"] => "value1"
["key2"] => "value2"
["key3"] => "value3"
)
Thanks! 谢谢!
edit: The data is in a string format ie: 编辑:数据为字符串格式,即:
$stringdata ='[ ["key1", "value1"], ["key2", "value2"], ["key3", "value3"] ]';
Use a loop and loop through the whole array and assign your values into a new array using the first element as key and the second element as value. 使用循环遍历整个数组,并使用第一个元素作为键,第二个元素作为值将值分配到新数组中。 Usually like this: 通常是这样的:
$new_array = array();
foreach($array as $arr) {
$new_array[$arr[0]] = $arr[1];
}
But to parse the string into an array I would take the following RegEx approach and then a loop: 但是要将字符串解析为数组,我将采用以下RegEx方法,然后进行循环:
$str = '[ ["key1", "value1"], ["key2", "value2"], ["key3", "value3"] ]';
preg_match_all('/(\[("(.*?)"), ("(.*?)")\])/i', $str, $matches);
//Now we have in $matches[3] and $matches[5] the keys and the values
//and we would now turn this into an array using a loop
$new_array = array();
for($k = 0; $k < count($matches[3]); $k++) {
$new_array[$matches[3][$k]] = $matches[5][$k];
}
See this live demo https://3v4l.org/u3jpl 观看此现场演示https://3v4l.org/u3jpl
Use functional approach with array_reduce 将功能性方法与array_reduce结合使用
<?php
$ar = [ ["key1", "value1"], ["key2", "value2"], ["key3", "value3"] ];
$newAr = array_reduce($ar, function($carry, $item) {
$carry[$item[0]] = $item[1];
return $carry;
});
var_dump($newAr);
Output: 输出:
array(3) {
["key1"]=>
string(6) "value1"
["key2"]=>
string(6) "value2"
["key3"]=>
string(6) "value3"
}
Here is a solution using json_decode . 这是使用json_decode的解决方案。
<?php
$json = json_decode('[["key1", "value1"], ["key2", "value2"], ["key3", "value3"]]');
$final = array();
foreach($json as $value) {
$final[] = array($value[0]=>$value[1]);
}
final
is the array in your required format. final
是您所需格式的数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.