Good day! My task would seem to be simple, but I can’t come up with a code in any way. There is a mysql table:

category date name1 2014-08-28 name2 2014-08-28 name3 2014-08-27 name3 2014-08-26 name1 2014-08-26 

At the output you need to get an array:

 array( 2014-08-28 => array(name1,name2), 2014-08-27 => array(name3), 2014-08-26 => array(name3,name1) ); 

I work in the codeigniter framework, maybe there is a tool in it to solve this problem more easily? Because I had to make two calls from the database, a bunch of cycles and it looks like a Chinese code, very ugly and illiterate, already ashamed to show.

  • Right in the database, you still will not do it sensibly. You will either receive an additional field-line, separated by commas, or many lines with duplicate date values ​​(in fact, a direct select). The easiest way is to pull everything out and just loop it off, already received in PHP. - etki
  • Well, I do not need to do it right in the database. just pull out for example the group by function two columns and already work with this data in php. but that’s exactly what I’m not getting - zinteco
  • one
    @zinteco, to compile the results by date in one line, you will need the GROUP_CONCAT() function, I will not say more, because I have never used it. > group by function is not really a function> already work with this data in php. but that’s what I’ve got for $ data = array (); foreach ($ results as $ result) {if (! isset ($ data [$ result ['date'])) {$ data [$ result ['date']] = array (); } $ data [$ result ['date']] [] = $ category; } voila, in $ data everything is sorted. - etki
  • There is not enough brackets if (! Isset ($ data [$ result ['date']])) {And where did you get $ category? - zinteco
  • @zinteco, $ result ['category'], of course. - etki

1 answer 1

Reply from comments

You can group the values ​​in the fields of suppliers and date , and then in a loop on the resulting table to form a two-dimensional array.

 <?php try { $pdo = new PDO( 'mysql:host=localhost;dbname=test', 'root', '', [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]); $query = "SELECT * FROM history GROUP BY suppliers, `date`"; $hst = $pdo->query($query); $result = []; while($history = $hst->fetch()) { $result[$history['date']][] = $history['suppliers']; } echo "<pre>"; print_r($result); echo "</pre>"; } catch (PDOException $e) { echo "Ошибка выполнения запроса: " . $e->getMessage(); }