The Codesee The Codesee - 1 year ago 53
PHP Question

Displaying part of JSON File

This is my JSON file:

{"message":"yes","info":{"ID":1,"Items":[{"Name":" Jim"},{"Name":" Bob"}]}}

Using the code below, I'm attempting to read the JSON file and echo each value of
(which should be Jim and Bob), however I'm being presented with the error:

syntax error, unexpected 'as' (T_AS), expecting ';'

$homepage = 'jsonfile';
$data = file_get_contents($homepage);
$users = $data['Items'];
for($users as $user) {
echo $user['Name'];

Answer Source

Check online

Decode the json string using json_decode and use a foreach to loop through the array. Get all the name into the $arr array and last implode them using implode.

$json = '{"message":"yes","info":{"ID":1, "Items":[{"Name":" Jim"},{"Name":" Bob"}]}}';
$result = json_decode ($json);

$arr = array();
foreach($result->info->Items as $value){
    $arr[] = $value->Name;
echo implode(", ", $arr); //Jim, Bob