Introduction
You can convert a JSON Object into an Array and String using PHP. This is a common requirement when working with APIs or external data sources. This guide provides a code snippet applicable to the PHP programming language that you can use to convert JSON to an Array or manipulate it as a string.
The Code Snippet
In the example below, $data is the JSON format in object form. We will decode it and loop through the result list to print the display names.
$data='{"resultList":[{"id":"1839","displayName":"Analytics","subLine":""},{"id":"1015","displayName":"Automation","subLine":""},{"id":"1084","displayName":"Aviation","subLine":""},{"id":"554","displayName":"Apparel","subLine":""},{"id":"875","displayName":"Aerospace","subLine":""},{"id":"1990","displayName":"Account Reconciliation","subLine":""},{"id":"3657","displayName":"Android","subLine":""},{"id":"1262","displayName":"Apache","subLine":""},{"id":"1440","displayName":"Acting","subLine":""},{"id":"710","displayName":"Aircraft","subLine":""},{"id":"12187","displayName":"AAC","subLine":""}, {"id":"20365","displayName":"AAT","subLine":""}, {"id":"7849","displayName":"AAP","subLine":""}, {"id":"20511","displayName":"AACR2","subLine":""}, {"id":"28585","displayName":"AASHTO","subLine":""}, {"id":"45191","displayName":"AAMS","subLine":""}]}';
// Decode the JSON data
$b = json_decode($data);
$i = 0;
// Loop through the object
while($b->{'resultList'}[$i])
{
print_r($b->{'resultList'}[$i]->{'displayName'});
echo "<br />";
$i++;
}
How It Works
- $data: Holds the raw JSON string.
- json_decode($data): Converts the JSON encoded string into a PHP variable (object).
- while loop: Iterates through the
resultListarray within the object. - print_r: Outputs the 'displayName' for each item found.