如何将String转换为JSON数组?

时间:2018-05-17 05:55:04

标签: php arrays string codeigniter

我正在集成第三方API,在响应中,他们发送的格式如下,但我想转换为JSON数组

响应:

$str = '[[name,class,rollno],[abhishek,tenth,556],[Rahul,Nine,20]]';
**Response is in String format

想要转换:

 [{"name":"abhishek","class":"tenth","rollno":"50"},{"name":"Rahul","class":"nine","rollno":"20"}]

2 个答案:

答案 0 :(得分:3)

你可以试试这个

$str = '[[name,class,rollno],[abhishek,tenth,556],[Rahul,Nine,20]]';

// match all inside [] e.g. name,class,rollno
preg_match_all('/\[?\[(.*?)\]/m', $str, $matches);

// set 1st match value as keys
$keys = explode(',', array_shift($matches[1]));

// map then combine keys with each data group
$result = array_map(function($e) use ($keys) {
    return array_combine($keys, explode(',', $e));
}, $matches[1]);

echo json_encode($result);

答案 1 :(得分:2)

你可以这样做。

<?php
$str = '[[name,class,rollno],[abhishek,tenth,556],[Rahul,Nine,20]]';
$str1 = ltrim($str,'[');
$str2 = rtrim($str1,']');
$ar = explode("],[",$str2);

$arkey = explode(',',$ar[0]);
for($i = 1; $i < count($ar); $i++){ 
    $val = explode(',', $ar[$i]);   
    $new[] = array($arkey[0] => $val[0],$arkey[1] => $val[1],$arkey[2] => $val[2]);
}

现在:

print_r(json_encode($new));

结果将是:

[{"name":"abhishek","class":"tenth","rollno":"556"},{"name":"Rahul","class":"Nine","rollno":"20"}]