I am integrating Third Party API and in Response, they are sending in the below format but I want to convert in JSON array
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"}]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.