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

时间:2016-03-26 15:36:23

标签: php arrays string parsing

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

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

进入:

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

谢谢!

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

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

3 个答案:

答案 0 :(得分:1)

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

$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

答案 1 :(得分:0)

使用array_reduce

的功能方法
FOUND

输出:

<?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);

答案 2 :(得分:0)

以下是使用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是您所需格式的数组。