简体   繁体   English

为什么这个json_encoded字符串不返回第四个元素?

[英]Why does this json_encoded string NOT return the fourth element?

I'm trying to echo a simple json_encoded file. 我试图回显一个简单的json_encoded文件。

<?php
$allMessages = file_get_contents("chatmessages.txt");

$allMessagesArr = explode(PHP_EOL, $allMessages);
$newObj = [];
var_dump($allMessagesArr);
foreach ($allMessagesArr as $thisLine) {
    // echo($thisLine . "\n");
    if (empty($thisLine) ) {

    } else {
        $thisLineArr = explode("|", $thisLine);

        $newObj[trim($thisLineArr[0])] = trim($thisLineArr[1]);
        // echo("here comes another one ".$thisLineArr[0] . " : ". $thisLineArr[1]."\n");
    }
}
$newObjForFront = json_encode($newObj);
echo($newObjForFront);

chatmessages.txt looks like this chatmessages.txt看起来像这样

bob|hello
jimmy|second try incoming again
sam|third try

bob|oh damn

I've echoed each individual line within the loop and the fourth element appears. 我已经在循环中回显了每一行,并且出现了第四个元素。 However, when I echo $newObjForFront, it's missing the last element. 但是,当我回显$ newObjForFront时,它缺少最后一个元素。 Any ideas why? 有什么想法吗?

When you create your final array $newObj in 当您在其中创建最终数组$newObj

$newObj[trim($thisLineArr[0])] = trim($thisLineArr[1]);

Your using the name as the index to the array. 您使用名称作为数组的索引。 As array indexes have to be unique, this means in fact the last entry overwrites the first one, so your actual output is... 由于数组索引必须是唯一的,因此实际上这意味着最后一个条目将覆盖第一个条目,因此您的实际输出为...

{"bob":"oh damn","jimmy":"second try incoming again","sam":"third try"}

So it is in fact the first message that is missing. 因此,实际上这是第一个丢失的消息。

Edit: 编辑:

If you wanted to just have all of the messages, then you could store them using 如果您只想拥有所有消息,则可以使用

$newObj[] = [ "user"=> trim($thisLineArr[0]), "msg" =>trim($thisLineArr[1])];

Which would give you the output as... 这将为您提供输出...

[{"user":"bob","msg":"hello"},{"user":"jimmy","msg":"second try incoming again"},{"user":"sam","msg":"third try"},{"user":"bob","msg":"oh damn"}]

$newObj[trim($thisLineArr[0])] = trim($thisLineArr[1]); this line will replace value with the last message of any username. 此行将值替换为任何用户名的最后一条消息。 if any username have multiple messages then only last message will be stored in the array. 如果任何用户名有多条消息,则仅最后一条消息将存储在数组中。

By creating multidimensional you can store multiple messages with the same username. 通过创建多维,您可以使用相同的用户名存储多条消息。 Check below code that may help you 检查以下可能对您有帮助的代码

$newObj[][trim($thisLineArr[0])] = trim($thisLineArr[1]);

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

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