new to php, I have read dozens of 'insert data into arrays' posts on the net, but none seem to describe my exact problem, (or I am too ignorant to recognize it) So here we go.
I get some data from a SQL database. I want to present this in a table. I have a working script that does this, but it has a slight malfunction, it doesn't show any empty results (rows) in the table. To get the desired result I my attempt 2.0 starts now with an empty table, with all the rows, and fill them in with data later.
$names = array('Alice', 'Bob', 'Charles', 'Dick', 'Emy');
for ($i=0; $i< count($names); $i++)
{
$empty_table[] = array("Name" => $names[$i], "Total" => 0, "Wins" => 0, "Losses" => 0) ;
}
This gives me an array that I can display as a table, with 5 data rows, each containing a value for the field with a Name key (Alice to Emy) and otherwise filled with values set to 0 for all other keys. It looks like:
Name Total Wins Losses
Alice 0 0 0
Bob 0 0 0
Charles 0 0 0
Dick 0 0 0
Emy 0 0 0
From the database I want to fill in the values that are 0, IF and only IF there is something in the database. I get the data with
for ($i=0; $i< count($names); $i++) {
$sql = "SELECT
SEVERAL THINGS
WHERE Something = '".$names[$i]."'";
$result = mysqli_query($conn,$sql);
// Not the real query obviously, but that part works and gives the intended result.
while ( $row = mysqli_fetch_assoc($result) ) {
Do something with the result in $row;
} // end while
} // end for
$row is an array with the same structure as one of the values of $empty_table. Example:$row could be: Array ( [Name] => Bob [Total] => 10 [Wins] => 7 [Losses] => 3 )
Now the question. How do I get the one dimension array $row into the two dimension array $empty_table (replacing the '0' values) , given that $empty_table always has a fixed 5 elements but there can be any number between 0 and 5 '$row's in the while loop depending on what is in the database?
If I try:
$empty_table[] = $row;
or
$empty_table[$row['Name']] = $row;
I only get rows added to the existing array with '0' values, not rows replaced. I do understand that the solution is between the '[]' but I can't figure out put something there that relates to the proper $row[].
var_dump($row);and add the result to your question .