Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP JSON Encoding within foreach loop

Tags:

json

php

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?

like image 418
user982124 Avatar asked Mar 09 '23 01:03

user982124


2 Answers

Problem:- Your are over-writing your $arr variable each-time inside foreach() loop.That cause the issue.

Solution:- Instead of over-writing, assign values to array like below:-

$arr = []; //create empty array

foreach($records as $record) {

    $arr[] = array(
                'ID' => $record->getField('propertyID');
                'name' => $record->getField('assignedName');
                'serialID' => $record->getField('serial');
                'tagID' => $record->getField('tag')
            );//assign each sub-array to the newly created array
} 
echo json_encode($arr);
like image 98
Anant Kumar Singh Avatar answered Mar 10 '23 15:03

Anant Kumar Singh


Add records to some kind of aggregation array and then json_encode it:

$items = [];
foreach($records as $record) {
    $items[] = [ 
        'ID' => $record->getField('propertyID'),
        'name' = $record->getField('assignedName'),
        'serialID' => $record->getField('serial'),
        'tagID' => $record->getField('tag'),
    ];
}

echo json_encode($items);
like image 33
u_mulder Avatar answered Mar 10 '23 14:03

u_mulder