简体   繁体   English

foreach覆盖消息数据php的每个迭代

[英]foreach overwriting each iteration of messages data php

I am getting the contents of mySQL data for messages, then I'm sorting through it per user to create a general array of messages. 我正在获取消息的mySQL数据的内容,然后按照每个用户对其进行排序以创建消息的常规数组。

IDEA Like So: 像这样的想法:

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

PHP so far 到目前为止的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;
    }

Though my output is 虽然我的输出是

 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
            )
        )
    )

Now I know it's overwriting either the array inside the user or it's overwriting the user altogether making it show the last push of the array. 现在我知道它覆盖了用户内部的数组,或者完全覆盖了用户,从而显示了数组的最后一次推送。 Not sure what I did wrong here, and thought maybe a fresh pair of eyes will help. 不知道我在这里做错了什么,并认为也许换一双新的眼睛会有所帮助。

Your problem is caused by the use of in_array() . 您的问题是由使用in_array()引起的。 That function checks for a value to be set in an array and not a key . 该函数检查要在数组中设置的 ,而不是

You need to replace this: 您需要替换以下内容:

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

with something like this: 像这样:

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

You can also use functions like key_exists() , etc. but you probably don't need this condition at all as you can set $conversations[$to_username][] even when $conversations[$to_username] does not exist. 您也可以使用诸如key_exists()等功能,但是您可能根本不需要此条件,因为即使$conversations[$to_username]不存在,也可以设置$conversations[$to_username][]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM