2016-11-22 90 views
0

救我使用Classfunction,試圖從mysqli while loopClass將數據發送到public $post=array();While循環的mysqli不陣列

我不知道爲什麼while loop僅從mysqli

代碼保存最後的數據

class Post extends Connection{ 

     public $post=array(); 

     function selectPost(){ 
      $query="select * from posts"; 
      $mysqli=$this -> connect(); 
      $select_all_post=$mysqli->query($query); 
      $x=1; 
      while($row=$select_all_post->fetch_object()){ 
       $this->post = array('Post No ' . $x=> array(
        'post_title' => $row->post_title, 
        'post_author' => $row->post_author, 
        'post_date' => $row->post_date, 
        'post_content' => $row->post_content 
       )); 
       $x++; 
      } 
      echo print_r($this->post); 
     } 
    } 

如果我嘗試使用[]在後陣,它的工作原理,但它使新的數組 Check Output

$this->post[] = array('Post No ' . $x=> array(
         'post_title' => $row->post_title, 
         'post_author' => $row->post_author, 
         'post_date' => $row->post_date, 
         'post_content' => $row->post_content 
        )); 

我的問題,如何從mysqli使用while loop發送的所有數據arrayClass

Like This

回答

2

你的類屬性只需使用後數作爲數組關鍵$this->post,而不是每一次索引一個新的數組:

$this->post['Post No ' . $x] = array(
    'post_title' => $row->post_title, 
    'post_author' => $row->post_author, 
    'post_date' => $row->post_date, 
    'post_content' => $row->post_content 
); 
1

由於您使用$這個 - > post = array(...。在你的while循環之後,最後的賦值是你查詢的最後一條記錄。

我不是s你將如何執行你的儲蓄。我假設在收集完帖子之後,你就會循環,這就是你插入權利的地方。

無論如何,考慮到你的代碼,你可以使用array_push。像這樣,

array_push($post, array('Post No ' . $x=> array(
     'post_title' => $row->post_title, 
     'post_author' => $row->post_author, 
     'post_date' => $row->post_date, 
     'post_content' => $row->post_content 
    ))); 
+0

這只是他已經嘗試過的第二部分的稍長版本 –