Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding rows to an array in PHP

I have loaded an associative array of records from a MySQL database table.

The array consists of 1 to 7 rows representing one week of entries, which might not have been entered for each day.

How can I insert blank rows into the array for the missing days so that I can easily display the data in a table?

I don't need to update the database with the blanks.

Example:

             Field1  Field2  Field3  Field4 .... Field#  
Record[0]
Record[1]
Record[2]
Record[3]
Record[4]
Record[5]
Record[6]

Field4 is the date as yyyy-mm-dd

I load the array automatically using a start date and end date

Some weeks there will be a Sun, Tue, and Fri or Mon, Tue, Wed, Fri & Sat.

like image 385
ChuckO Avatar asked May 24 '10 20:05

ChuckO


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).

Does += work on arrays in PHP?

The + operator in PHP when applied to arrays does the job of array UNION. $arr += array $arr1; effectively finds the union of $arr and $arr1 and assigns the result to $arr .

What is Array_keys () used for in PHP?

The array_keys() is a built-in function in PHP and is used to return either all the keys of and array or the subset of the keys. Parameters: The function takes three parameters out of which one is mandatory and other two are optional.

What does => mean in PHP?

=> is the separator for associative arrays. In the context of that foreach loop, it assigns the key of the array to $user and the value to $pass .


1 Answers

this is simple: Do you know how many "Fields" you have for each day? let's say it's "num of fields"

$records = array_fill(0, 7, array_fill(0, <num of fields>, ''));

what this does is it creates a blank array from [0] to [6] and for each array element it inserts another array of "Fields", with "num of fields", each of which is set to an empty string ''.

Now that you have this, you read your data from the mysql table and if you selectively assign $records by index (i'm assuming), the rest of them will stay blank.

Keep in mind that you can reassign an element of $records array by using something like

$records[5] = array('New value', 'Field2 value');

which is what you do when you read data from mysql table.

Do you use some kind of index in your mysql table to correspond to the numbered day in a week?

comment here if you get stuck with mysql part.

like image 134
hndcrftd Avatar answered Sep 23 '22 03:09

hndcrftd