user1532602 user1532602 - 2 months ago 6
JSON Question

Adding columns to existing php arrays

Using PHP let's assume that I have successfully read a record from a MySQL table using the fetch_object method and I am holding the row data in a variable call $output:

while($row = $result->fetch_object())
{
$output[] = $row;
}


If I wanted to add two additional fields: "cls" and "parentID" to $output as if they were apart of $row, how would I accomplish this? Thanks!

Answer

Loop through the array by reference and add what you want after the while loop:

foreach( $output as &$row) {
    $row->cls = 0;
    $row->parentID = 1;
}

You can also do this within the while loop:

while($row = $result->fetch_object()) {
    $row->cls = 0;
    $row->parentID = 1;
    $output[] = $row;
}
Comments