adding elements in an array day-wise from mysql database

Go To


How can I get the record values in the database to be sorted like this in an array. Supose I am adding the day no.

 [0] => array=>'id'=>'26' 'date'=>'26'

 [1] => array=>'id'=>'27' 'date'=>'27',
        array=>'id'=>'28' 'date'=>'27',
        array=>'id'=>'29' 'date'=>'27'

 [2] => array=>'id'=>'30' 'date'=>'29'

 [3] => array=>'id'=>'31' 'date'=>'31',
        array=>'id'=>'32' 'date'=>'31',
        array=>'id'=>'33' 'date'=>'31'

Basically, I want to add an array to the same index if the next id contains a record with the same date (day no) of the month. Otherwise add it normally.

Right now, My function is adding the rows of the record without sorting it in the format I want it to be in.

The reason I want it to be in this format is because, I need to run the foreach, and if 1 day contains 2 records, then it will append another <li> into my unordered list.

public function getArticles()
        $sql = 'CALL getArticles()';        
        $articles = Array();

        if (Model::getConnection()->multi_query($sql)) {
            do {
                if ($result = Model::getConnection()->store_result()) {
                    while ($row = $result->fetch_assoc()) {     
            } while (Model::getConnection()->next_result());
        return $articles;
2012-04-03 22:26
by SupaOden


I don't recognize what some of your code is doing, but I think this is the important part.

while ($row = $result->fetch_assoc()) {     
    if (!isset($articles[$row['date']])) {
        $articles[$row['date']] = array();
    $articles[$row['date']][] = $row;                        

The only difference will be that your array will be keyed on the date instead of incrementing from zero. If you really want it reindexed, you can do...

2012-04-03 22:29
by savinger


As savinger pointed out, there is alot of functionality in your code which I don't really know, so I've included comments to indicate whereabouts the process is:

// Start of your loop

// $value is what you're getting from the DB...

$array_search = array_search($value,$main_array);

   // If this value already exists, we need to add
   // this value in +1 of its current value
   $main_array[$array_search][] = $value + 1;
   // Make a new array key and add in the value
   $main_array[] = $value;

// End of your loop
2012-04-04 01:08
by hohner