1

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"}]
4
  • Cool. Good luck. Let us know if you run into any issues at some point when you're trying to do it. If you do, then show us what you've tried and where the issue is, since SO isn't a free coding service. Please read: How to create a Minimal, Complete, and Verifiable example and also How do I ask a good question? Commented May 17, 2018 at 5:57
  • @MagnusEriksson i didn't get any idea how i do that, main issue is that i am getting response in string. Can you help me ? Commented May 17, 2018 at 5:59
  • 1
    If that is the actual string you're getting, then you have more issues, since that's not a valid JSON string. Commented May 17, 2018 at 6:00
  • yes I am getting the response in actual String, not a JSON string. Commented May 17, 2018 at 6:10

2 Answers 2

3

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);
Sign up to request clarification or add additional context in comments.

Comments

2

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"}]

1 Comment

Thanks a lot, @Kawaljeet Singh.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.