Jump to content

Reading simple json


dweb

Recommended Posts

Hi

 

I have this json file

 

{"user":"RD32","time":"14:00","type":"staff"}
{"user":"XC12","time":"21:00","type":"management"}
{"user":"YG89","time":"09:00","type":"staff"}

 

and I want to pull just "staff" from it and output like

 

user: RD32

time: 14:00

-----

user: YG89

time: 09:00

 

is that possible?

Link to comment
https://forums.phpfreaks.com/topic/289912-reading-simple-json/
Share on other sites

Yes you would need to loop over each user in the array and check that the value of the type index is set to staff

$json_string = '[{"user":"RD32","time":"14:00","type":"staff"},
{"user":"XC12","time":"21:00","type":"management"},
{"user":"YG89","time":"09:00","type":"staff"}]';


$users = json_decode($json_string,1);

$staffUsers = array();
foreach($users as $user)
{
    if(isset($user['type']) && $user['type'] == 'staff')
    {
        $staffUsers[] = $user;
    }
}

print_r($staffUsers);

/* Returns
Array
(
    [0] => Array
        (
            [user] => RD32
            [time] => 14:00
            [type] => staff
        )

    [1] => Array
        (
            [user] => YG89
            [time] => 09:00
            [type] => staff
        )
)
*/
Link to comment
https://forums.phpfreaks.com/topic/289912-reading-simple-json/#findComment-1485298
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.