返回的数组让我很困惑

时间:2014-02-15 12:46:40

标签: php mysql sql arrays

我遇到了PHP和MySQL即时消息服务的问题。我的代码应该返回这样的东西(不要担心用户和值):

数组([0] =>数组([日期] => 1322254667 [文字] =>一个[user_name] => bob))

但实际上它会回归:

array(1){[0] => array(4){[“date”] => string(10)“1392464979”[“unread”] => NULL [“text”] => string(9)“FOR PETER”[“user_name”] => string(5)“Peter”}}

作为PHP和MySQL的新手,我不知道如何解决这个问题。

我确信这对你来说非常明显,对不起。

请帮帮我。

提前谢谢。

private_message.inc.php:

    <?php

    // Fetches a summary of the conversations.
    function fetch_conversation_summary(){
            $sql = "SELECT
                                    `conversations`.`conversation_id`,
                                    `conversations`.`conversation_subject`,
                                    MAX(`conversations_messages`.`message_date`) AS `conversation_last_reply`,
                                    MAX(`conversations_messages`.`message_date`) > `conversations_members`.`conversation_last_view` AS `conversation_unread`
                            FROM `conversations`
                            LEFT JOIN `conversations_messages` ON  `conversations`.`conversation_id` = `conversations_messages`.`conversation_id`
                            INNER JOIN `conversations_members` ON `conversations`.`conversation_id` = `conversations_messages`.`conversation_id`
                            WHERE `conversations_members`.`user_id` = {$_SESSION['user_id']}
                            AND `conversations_members`.`conversation_deleted` = 0
                            GROUP BY `conversations`.`conversation_id`
                            ORDER BY `conversation_last_reply` DESC";

            $result = mysql_query($sql);

            $conversations = array();

            while (($row = mysql_fetch_assoc($result)) !== false){
                    $conversations[] = array(
                            'id'                            => $row['conversation_id'],
                            'subject'                       => $row['conversation_subject'],
                            'last_reply'            => $row['conversation_last_reply'],
                            'unread_messages'       => ($row['conversation_unread'] == 1),
                    );
            }

            return $conversations;
    }

// Fetches all of the messages in the given converstion.
function fetch_conversation_messages($conversation_id){
    $conversation_id = (int)$conversation_id;

    $sql = "SELECT
  `conversations_messages`.`message_date`,
  `conversations_messages`.`message_text`,
  `users`.`user_name`
FROM `conversations_messages`
INNER JOIN `users` ON `conversations_messages`.`user_id` = `users`.`user_id`
WHERE `conversations_messages`.`conversation_id` = {$conversation_id}
ORDER BY `conversations_messages`.`message_date` DESC";

    $result = mysql_query($sql);
    var_dump($result);
    $messages = array();

    while (($row = mysql_fetch_assoc($result)) !== false){
            $messages[] = array(
                    'date'          => $row['message_date'],
                    'unread'        => $row['message_unread'],
                    'text'          => $row['message_text'],
                    'user_name'     => $row['user_name'],
            );


    }
var_dump($messages);}

    // Sets the last view time to the current time for the given conversation.
    function update_conversation_last_view($conversation_id){
            $conversation_id = (int)$conversation_id;
            $time = time() + 18000;
            $sql ="UPDATE `conversations_members`
                            SET `conversation_last_view` = {$time}
                            WHERE `conversation_id` = {$conversation_id}

                            AND `user_id` = {$_SESSION['user_id']}";

            mysql_query($sql);     
    }

     // Creates a new conversation, making the given users a member.
    function create_conversation($user_ids, $subject, $body){
            $subject        = mysql_real_escape_string(htmlentities($subject));
            $body           = mysql_real_escape_string(htmlentities($body));

            mysql_query("INSERT INTO `conversations` (`conversation_subject`) VALUES ('{$subject}')");

            $conversation_id = mysql_insert_id();

            $sql = "INSERT INTO `conversations_messages` (`conversation_id`, `user_id`, `message_date`, `message_text`)
                            VALUES ({$conversation_id}, {$_SESSION['user_id']}, UNIX_TIMESTAMP(), '{$body}')";

            mysql_query($sql);

            $values = array("({$conversation_id}, {$_SESSION['user_id']}, UNIX_TIMESTAMP(), 0)");

            foreach ($user_ids as $user_id){
                    $user_id = (int)$user_id;

        $values = array("({$conversation_id}, {$_SESSION['user_id']}, UNIX_TIMESTAMP(), 0)");            }

            $sql = "INSERT INTO `conversations_members` (`conversation_id`, `user_id`, `conversation_last_view`, `conversation_deleted`)
                            VALUES " . implode(", ", $values);

                            mysql_query($sql);
    }


// Checks to see if the given user is a member of the given conversation.
function validate_conversation_id($conversation_id){
    $conversation_id = (int)$conversation_id;
    echo 'Conversation ID: '.$conversation_id.'<br />';
    echo 'User ID: '.$_SESSION['user_id'].'<br />';
    $sql = "SELECT COUNT(1)
            FROM `conversations_members`
            WHERE `conversation_id` = {$conversation_id}
            AND `user_id` = {$_SESSION['user_id']}
            AND `conversation_deleted` = 0";

            $result = mysql_query($sql);

            return (mysql_result($result, 0) == 1);
}

// Deletes (or marks as deleted) a given conversation.
function delete_conversation($conversation_id){
            $conversation_id = (int)$conversation_id;

            $sql = "SELECT DISTINCT `conversation_deleted`
                            FROM `conversations_members`
                            WHERE `user_id` != {$_SESSION['user_id']}
                            AND `conversation_id` = {$conversation_id}";

            $result = mysql_query($sql);

            //if (mysql_num_rows($result) == 1 && mysql_result($result, 0) == 1){
      if (mysql_num_rows($result) == 0){
                    mysql_query("DELETE FROM `conversations` WHERE `conversation_id` = {$conversation_id}");
                    mysql_query("DELETE FROM `conversations_members` WHERE `conversation_id` = {$conversation_id}");
                    mysql_query("DELETE FROM `conversations_messages` WHERE `conversation_id` = {$conversation_id}");
                    echo 'actually deleting';
            }else{
                    $sql = "UPDATE `conversations_members`
                                    SET `conversation_deleted` = 1
                                    WHERE `conversation_id` = {$conversation_id}
                                    AND `user_id` = {$_SESSION['user_id']}";

                    mysql_query($sql);
                    echo 'flagging as deleted';

            }
    }
    ?>

view_conversation.page.inc.php:

    <?php



    $errors = array();
    $valid_conversation = (isset($_GET['conversation_id']) && validate_conversation_id($_GET['conversation_id']));
    if ($valid_conversation === false){
            $errors[] = 'Invalid Conversation ID.';
    }
    if (isset($_POST['message'])){
            if (empty($_POST['message'])){
                    $errors[] = 'You must enter a message.';
            }

            if (empty($errors)){
                    add_conversation_message($_GET['conversation_id'], $_POST['message']);
            }
    }

 if (empty($errors) === false){
        foreach ($errors as $error){
            echo $error;
        }
}


    if ($valid_conversation){
            /*if (isset($_POST['message'])){
                    update_conversation_last_view($_GET['conversation_id']);*/
                    $messages = fetch_conversation_messages($_GET['conversation_id']);
            }else{
                    $messages = array();
                    update_conversation_last_view($_GET['conversation_id']);
            }


    ?>

    <a href="index.php?page=inbox">Inbox</a>
    <a href="index.php?page=logout">Logout</a>

            <form action="" method="post">
                    <p><textarea name="message" rows="10" cols="110"></textarea></p>
                    <p><input type="submit" value="Add Message" /></p>
            </form>

            <?php
            //var_dump( $messages );
            if($messages){
            foreach ($messages as $message){
            ?>
            <?php if ($message['unread']) echo 'unread'; ?>


    <?php

    }}
    ?>

3 个答案:

答案 0 :(得分:1)

var_dump()会向您的阵列添加其他信息。使用print_r()按原样查看数组!

答案 1 :(得分:1)

实际上

Array ( [0] => Array ( [date] => 1322254667 [text] => one [user_name] => bob ) )

array(1) { [0]=> array(4) { ["date"]=> string(10) "1392464979" ["unread"]=> NULL ["text"]=> string(9) "FOR PETER" ["user_name"]=> string(5) "Peter" } }

是一样的。 var_dump显示变量的所有信息,如大小,类型等,就像您的情况一样。 See here

要查看数组结构,您可以使用以下代码行。

echo '<pre>'; print_r($array); die();

答案 2 :(得分:-1)

你已宣布

$conversations[] = array ('date'          => $row['message_date'],
                'unread'        => $row['message_unread'],
                'text'          => $row['message_text'],
                'user_name'     => $row['user_name'],);

这意味着[] =数组 再加上你也写了两次这样的数组 检查