2014-10-18 36 views
1

我正在爲消息獲取mySQL數據的內容,然後通過它對每個用戶進行排序以創建消息的一般數組。foreach覆蓋消息數據的每次迭代php

IDEA像這樣:

Array(
    ["Mr.EasyBB"] => Array(
        [0] => array(//message data here) 
        [1] => array(//message data here) 
        ... 
       ); 
); 

PHP到目前爲止

$messages = $controller->loadResult(
    "SELECT * FROM messages WHERE from_username='$username' AND from_uid='$uid'" 
    ); 
if($messages){ 
    foreach($messages as $data){ 
     $to_username = strtolower($data["to_username"]); 
      if(!in_array($to_username,$conversations)){ 
       $conversations[$to_username] = array(); 
      } 
     $conversations[$to_username][]= $data; 
    } 

雖然我的輸出是

Array 
(
    [ianbruce] => Array 
     (
     [0] => Array 
      (
       [0] => 231 
       [to_uid] => 231 
       [1] => 0001 
       [from_uid] => 0001 
       [2] => IanBruce 
       [to_username] => IanBruce 
       [3] => Mr.EasyBB 
       [from_username] => Mr.EasyBB 
       [4] => n 
       [deleted] => n 
       [5] => n 
       [sent_deleted] => n 
       [6] => Howdy Again my Friend 
       [message] => Howdy Again my Friend 
       [7] => 2014-10-18 00:01:04 
       [to_timestamp] => 2014-10-18 00:01:04 
       [8] => 0000-00-00 00:00:00 
       [from_timestamp] => 0000-00-00 00:00:00 
       [9] => y 
       [from_seen] => y 
       [10] => n 
       [to_seen] => n 
      ) 
     ) 
    ) 

現在我知道它的覆蓋或者用戶內部的陣列,或者它覆蓋用戶完全讓它顯示陣列的最後一個推動。不知道我在這裏做錯了什麼,並認爲也許一雙新鮮的眼睛會有所幫助。

回答

4

您的問題是由使用in_array()引起的。該功能檢查設置在一個數組中而不是密鑰

您需要替換這樣的:像這樣的東西

if(!in_array($to_username,$conversations)){ 

if(!isset($conversations[$to_username])){ 

您也可以使用功能,如key_exists()等,但你也許並不需要這個條件在所有因爲即使$conversations[$to_username]不存在,您也可以設置$conversations[$to_username][]

+1

知道我錯過了一些東西:D – EasyBB 2014-10-18 19:22:24