-1

How to convert with php this json

    [{"value":"jquery"},{"value":"bootstrap"}]

to

jquery, bootstrap

and vice versa ?

Secux
  • 19
  • 6

1 Answers1

1

First you need to json_decode() the string into an array of objects. Then use array_column() to pull the value fields from those objects. Last you implode() the array into your comma separated value string.

$jsonString = '[{"value":"jquery"},{"value":"bootstrap"}]';
$array = json_decode($jsonString);
$array2 = array_column($array, "value");
$csv = implode(", ", $array2);

Going the other way is more complicated. explode() is the opposite of implode() and json_encode() is the opposite of json_decode(), but there's no built in way to reverse array_column() like you want. Because of that you need to array_map() your values into an object manually with your own function:

$array3 = explode(", ", $csv);    
$array4 = array_map(function ($val){ 
    $obj = (object)[];
    $obj->value = $val;
    return $obj;
}, $array3);
$jsonString2 = json_encode($array4);

See it working on 3V4L

Andrew
  • 1,448
  • 1
  • 20
  • 33