Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding columns to existing php arrays

Tags:

json

arrays

php

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!

like image 712
Elcid_91 Avatar asked Sep 05 '12 16:09

Elcid_91


People also ask

Can you add to an array in PHP?

Definition and Usage. The array_push() function inserts one or more elements to the end of an array. Tip: You can add one value, or as many as you like. Note: Even if your array has string keys, your added elements will always have numeric keys (See example below).

How does array_ column work?

array_column() returns the values from a single column of the array , identified by the column_key . Optionally, an index_key may be provided to index the values in the returned array by the values from the index_key column of the input array.

What are the 3 types of PHP arrays?

In PHP, there are three types of arrays: Indexed arrays - Arrays with a numeric index. Associative arrays - Arrays with named keys. Multidimensional arrays - Arrays containing one or more arrays.


2 Answers

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;
}
like image 163
nickb Avatar answered Oct 12 '22 21:10

nickb


Since you changed the code snippet in your question, try this instead now (updated version):

while(...) {
   $row->cls = ...;
   $row->parentID = ...;
   $output[] = $row;
}
like image 42
Marc B Avatar answered Oct 12 '22 23:10

Marc B