PHP:将字符串[“key”,“value”]解析为关联数组


PHP: Parse string ["key", "value"] into associative array

如何将以下格式的字符串解析为关联数组?

[ ["key1", "value1"], ["key2", "value2"], ["key3", "value3] ]

进入:

Array
(
    ["key1"] => "value1"
    ["key2"] => "value2"
    ["key3"] => "value3"
)

谢谢!

编辑:数据采用字符串格式,即:

$stringdata ='[ ["key1", "value1"], ["key2", "value2"], ["key3", "value3"] ]';

使用循环和循环遍历整个数组,并使用第一个元素作为键,第二个元素作为值将值分配到一个新数组中。通常是这样的:

$new_array = array();
foreach($array as $arr) {
    $new_array[$arr[0]] = $arr[1];
}

但要将字符串解析为数组,我将采用以下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];
}

查看此实时演示https://3v4l.org/u3jpl

使用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);

输出:

array(3) {
  ["key1"]=>
  string(6) "value1"
  ["key2"]=>
  string(6) "value2"
  ["key3"]=>
  string(6) "value3"
}

这里有一个使用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是所需格式的数组。