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!
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).
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.
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.
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;
}
Since you changed the code snippet in your question, try this instead now (updated version):
while(...) {
$row->cls = ...;
$row->parentID = ...;
$output[] = $row;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With