PHP JSON Encoding within foreach loop

Viewed 6846

I'm trying to generate the following JSON data:

[
    {
        "ID": "A1000",
        "name": "John Simpson",
        "serialID": "S41234",
        "tagID": "ABC6456"
    },  
    {
        "ID": "B2000",
        "name": "Sally Smith",
        "serialID": "B5134536",
        "tagID": "KJJ451345"
    },
    {
        "ID": "A9854",
        "name": "Henry Jones",
        "serialID": "KY4239582309",
        "tagID": "HYG452435"
    }
]

from within a PHP foreach loop which looks like this:

foreach($records as $record) {

        $ID = $record->getField('propertyID');
        $name = $record->getField('assignedName');
        $serialID = $record->getField('serial');
        $tagID = $record->getField('tag');

    }

I've tried using:

$arr = array('ID' => $ID, 'name' => $name, 'serialID' => $serialID, 'tagID' => $tagID);

which works for each record within the loop, but can't work out the syntax to join them together into a single JSON data string?

6 Answers
Related