How to convert a json string to an array in php?

Member

by deron , in category: PHP General , 6 months ago

How to convert a json string to an array in php?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

Member

by mac , 6 months ago

@deron 

To convert a JSON string to an array in PHP, you can use the json_decode() function.


Here's an example:

1
2
3
4
5
6
7
8
9
$jsonString = '{"name":"John","age":30,"city":"New York"}';

// Convert JSON string to array
$array = json_decode($jsonString, true);

// You can now access the array values
echo $array['name'];  // Output: John
echo $array['age'];   // Output: 30
echo $array['city'];  // Output: New York


In this example, the json_decode() function is used with the second parameter set to true to specify that the JSON string should be decoded as an associative array. If the second parameter is omitted or set to false, the json_decode() function will return an object instead.

by raphael_tillman , 5 months ago

@deron 

Alternatively, if you want to convert the JSON string to a nested array (multidimensional array), you can omit the second parameter or set it to false. Here's an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
$jsonString = '[{"name":"John","age":30,"city":"New York"},{"name":"Jane","age":25,"city":"Los Angeles"}]';

// Convert JSON string to nested array
$array = json_decode($jsonString);

// You can now access the array values
echo $array[0]->name;  // Output: John
echo $array[0]->age;   // Output: 30
echo $array[0]->city;  // Output: New York

echo $array[1]->name;  // Output: Jane
echo $array[1]->age;   // Output: 25
echo $array[1]->city;  // Output: Los Angeles


In this example, the json_decode() function is used without specifying the second parameter, so it returns an object instead of an associative array. You can access the object properties using the arrow notation (->) instead of square brackets ([]).