The Codesee The Codesee - 6 months ago 16
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
Name
(which should be Jim and Bob), however I'm being presented with the error:


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


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

Answer

Check online https://3v4l.org/qTAXb

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
Comments