mardi 5 mai 2015

Include blank values in array from foreach statement

I am using two mySQL tables to create a javascript chart. Table A:

id |   date   | attended
1  |2015-01-14| 3
2  |2015-01-20| 4
3  |2015-01-31| 2

Table B:

id | name |   date
1  | dog  |2015-01-14
2  | cat  |2015-01-14
3  | fish |2015-01-30

Using this code:

<?php
    $sql = "SELECT TableB.*
    FROM TableB
    RIGHT JOIN TableA
    ON TableB.date=TableA.date
    ORDER BY TableA.date";
    $names = $con->query($sql);
?>
var namegroup=[<?php
$info = array();
while($row=$names->fetch_assoc())  {
    $date = $row['date'];
    $name = $row['name'];
    $info[$date][] = $name;
}
foreach ($info as $date => $values) {
    echo '"';
    foreach($values as $value) {
        echo $value . ',';
    }
    echo '",';
}
?>];

I am able to look at Table A and get the rows in Table B whose dates are the same and following this answer was able do a foreach that provides me with this array:

var namegroup=[",","dog,cat,","fish,"]

The problem is that any blank data (which I want) is grouped at the beginning of the array and I want it to remain in an order based on the date to get an array like so:

var namegroup=["dog,cat,",",","fish,"]

Any help would be much appreciated. Also I am sure that my code is not perfect as I am somewhat teaching myself mySQL and PHP so if there are any suggestions for cleaner/better code feel free to weigh in. Thanks.

Aucun commentaire:

Enregistrer un commentaire