-3

I have a string format like this:

"Android Development : 1, Android Studio : 1, Kotlin : 1, Java : 1, Model-View-Presenter (MVP) : 0, "

I need to convert it to JSON format which looks like this:

[{'id': 1, 'name': "Android Development"}, {'id': 2, 'name': "Android Studio"},{'id': 3, 'name': "Kotlin"}, {'id': 4, 'name': "Java"}, {'id': 5, 'name': "Model-View-Presenter (MVP)"}]
  • The question doesn't appear to include any attempt at all to solve the problem. Please edit the question to show what you've tried, and show a specific roadblock you're running into with [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve). For more information, please see [How to Ask](https://stackoverflow.com/help/how-to-ask). – Andreas Oct 22 '19 at 04:37
  • Do you want to do anything with the numeric values in the string? – Nick Oct 22 '19 at 04:40
  • Have a look on this article https://stackoverflow.com/questions/15609306/convert-string-to-json-array – Sajib Talukder Oct 22 '19 at 04:49
  • @SajibTalukder: the article you provide tried to parse a structured JSON string to java's object while OP wants to restructure a string to JSON format. – catcon Oct 22 '19 at 05:02

4 Answers4

1

You could try code:

$str = "Android Development : 1, Android Studio : 1, Kotlin : 1, Java : 1, Model-View-Presenter (MVP) : 0,";
$arr1 = explode(",",$str);
$result = array();

foreach ($arr1 as $value) {
    $arr2 = explode(":",$value);
    if(count($arr2)>0)
    {
        $result[] = $arr2[0];
    }
}
var_dump($result);
Au Nguyen
  • 655
  • 4
  • 12
0

Split the string with , then save the content before : as name.

$result = [];
$string = "Android Development : 1, Android Studio : 1, Kotlin : 1, Java : 1, Model-View-Presenter (MVP) : 0, ";
$array = explode(',',$string);
$id = 1;
foreach($array as $str){
    if($pos = strpos($str,":")){
        $result[] = array(
            'id' => $id++,
            'name' => trim(substr($str,0,$pos))
        );
    }
}
print_r(json_encode($result));
LF00
  • 27,015
  • 29
  • 156
  • 295
0

You can try something like this:

$string = "Android Development : 1, Android Studio : 1, Kotlin : 1, Java : 1, Model-View-Presenter (MVP) : 0, ";

$array1 = explode(',', $string);
$result = [];
foreach ($array1 as $key => $value) {
     $value = trim($value);
     if (!empty($value)) {
          $array2 = explode(':', $value);
          $result[$key]['id'] = $key;
          $result[$key]['name'] = $array2[0];
      }
 }

echo json_encode($result);
akshaypjoshi
  • 1,245
  • 1
  • 15
  • 24
0

try this:

$string="Android Development : 1, Android Studio : 1, Kotlin : 1, Java : 1, Model-View-Presenter (MVP) : 0, ";
    $arr= preg_split( '/(,|:)/', $string);
    $output=[];
    for($i=0;$i<count($arr)-1;$i+=2)
        $output[]=[
        'name'=>$arr[$i],
        'id'=>(int)$arr[$i+1],
        ];

        echo json_encode($output);