简体   繁体   English

如何将String转换为JSON数组?

[英]How can i convert String into JSON array?

I am integrating Third Party API and in Response, they are sending in the below format but I want to convert in JSON array 我正在集成第三方API,并且在响应中,它们以以下格式发送,但我想在JSON数组中进行转换

Response: 响应:

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

Want to convert: 要转换:

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

You can try this 你可以试试这个

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

You can do it like following. 您可以按照以下步骤进行操作。

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

Now : 现在:

print_r(json_encode($new));

Result will be : 结果将是:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM