Iterable Array / Hash Map

Edit: Nico Parody's answer is correct. I will eventually return to asking why, but for now I will just take it as it is and hope that nothing else will succeed.

I have a table with three fields: "date", "name", "location". I want to group all the records selected from this table, depending on their date.

Having copied the following code from php mysql group by date in the format yyyy-mm-dd , I managed to get this array, date β†’ name:

$result = mysqli_query($con,"SELECT date, name, location FROM events"); while($row = mysqli_fetch_array($result)) { $foo[$row['date']][]=$row['name']; } 

Everything is fine, I can repeat it without any problems. Now I want to save all row columns as a value for the date key, so I'm trying to save the entire row as a value:

 $result = mysqli_query($con,"SELECT date, name, location FROM events"); while($row = mysqli_fetch_array($result)) { $foo[$row['date']][]=$row; } 

And now I can’t repeat it. count ($ rowCol) seems to give me nr columns in the entire array for any keys, not just one. How can I repeat it?

 foreach($foo as $date => $events) { echo $date . ": "; // this is okay foreach($events as $key => $rowCol){ for ($i = 0; $i<count($rowCol); $i++) { echo $rowCol[$i] . " "; } } } 
+4
source share
4 answers
 for ($i = 0; $i<count($rowCol); $i++) { echo $rowCol[$i] . " "; } 

$ rowCol has the double number of fields you expect, since mysqli_fetch_array () selects both an associative and a numerical array. In this way,

 for ($i = 0; $i<(count($rowCol)/2); $i++) { echo $rowCol[$i] . " "; } 

must work.

+1
source

Can you tell us what the output of this code is? (show plain text, without HTML):

 foreach($foo as $date => $event) { echo $date . ": "; foreach($event as $key => $value){ print_r($value); } echo "\n"; } 

Original answer:

$events contains one event, your code should look something like this:

 foreach($foo as $date => $event) { echo $date . ": "; foreach($event as $key => $value){ echo $value . " "; } echo "\n"; } 
+1
source
 for ($i = 0; $i<count($rowCol); $i++) { echo $rowCol[$i] . " "; } 

this piece of code does not work because rowCol is an associative array + a numeric array. Try replacing mysqli_fetch_array with mysqli_fetch_row

+1
source

Replace:

  for ($i = 0; $i<count($rowCol); $i++) { echo $rowCol[$i] . " "; } 

Across

  foreach($rowCol as $k =>$v) { echo $v . " "; } 
+1
source

Source: https://habr.com/ru/post/1486906/


All Articles