2012-04-03 160 views
0

如何獲取數據庫中的記錄值,以便像這樣在數組中排序。 Supose我加入了第一天。從mysql數據庫中每天向數組中添加元素

array 
[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' 

基本上,我想這個月的陣列添加到相同的索引,如果下一個ID包含相同日期的記錄(天無)。否則,正常添加它。

眼下,我的功能被添加記錄的行,而不在我希望它是格式分類整理。

我希望它是這種格式是因爲,我需要運行的原因該foreach,如果1天包含2條記錄,那麼它會將另一個<li>附加到我的無序列表中。

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()) {  
         array_push($articles,$row);       
        } 
       $result->free(); 
       } 
      } while (Model::getConnection()->next_result()); 
     } 
     return $articles; 
} 

回答

0

我不承認你的一些代碼在做什麼,但我認爲這是重要的部分。

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

唯一的區別是你的陣列將在date被鍵入,而不是從零遞增。如果你真的想要重建索引,你可以做...

array_values($articles); 
0

由於savinger指出,有很多在你的代碼,我真的不知道的功能,所以我已經包括了意見,表示行蹤該過程是:

// Start of your loop 

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

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

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

// End of your loop