gpt4 book ai didi

php - 如何将元素添加到 php 数组而不显示为新数组

转载 作者:行者123 更新时间:2023-11-28 23:21:37 25 4
gpt4 key购买 nike

下面代码的目的是从一个 mysql 表中提取消息,并将它们中的每一个放在一个数组中,每个输出周围都有 {}。如您所见,每个输出都包含各种参数,并且本身就是一个数组。代码的作用是每次处理循环时,在稍后转换成的 JSON 数组中,它将输出包装在 [] 中,因此现在创建了一个新数组。我得到的是:

[{"sender":"ll","message":"blah","timestamp":"2016-12-21 14:43:04","username":"","msgtype":"","threadid":"32629016712222016034323"},{"sender":"kk","message":"blahblah","timestamp":"2016-12-21 14:43:23","username":"","msgtype":"","threadid":"32629016712222016034323"},{"sender":"ll","message":"blahblahblah","timestamp":"2016-12-21 14:43:47","username":"","msgtype":"","threadid":"32629016712222016034323"}],[{"sender":"ll","message":"blahblahblahblah","timestamp":"2016-12-21 14:43:04","username":"","msgtype":"","threadid":"92337321312222016034304"},{"sender":"kk","message":"blahblahblahblahblah","timestamp":"2016-12-21 14:44:05","username":"","msgtype":"","threadid":"92337321312222016034304"}]]

我想要的是:

[{"sender":"ll","message":"blah","timestamp":"2016-12-21 14:43:04","username":"","msgtype":"","threadid":"32629016712222016034323"},{"sender":"kk","message":"blahblah","timestamp":"2016-12-21 14:43:23","username":"","msgtype":"","threadid":"32629016712222016034323"},{"sender":"ll","message":"blahblahblah","timestamp":"2016-12-21 14:43:47","username":"","msgtype":"","threadid":"32629016712222016034323"}],{"sender":"ll","message":"blahblahblahblah","timestamp":"2016-12-21 14:43:04","username":"","msgtype":"","threadid":"92337321312222016034304"},{"sender":"kk","message":"blahblahblahblahblah","timestamp":"2016-12-21 14:44:05","username":"","msgtype":"","threadid":"92337321312222016034304"}]

我如何继续在这里获得正确的结果?

$data = array ();
foreach($threads as $threadid){
$sql = ("SELECT sender,message,timestamp,username,msgtype,threadid FROM Messages WHERE threadid = '$threadid' AND subject = '' AND timestamp > '$newtimestamp' ORDER BY timestamp");
$arrayOfObjects = $conn->query($sql)->fetchAll(PDO::FETCH_OBJ);
$data[] = $$arrayOfObjects;
}

仅供引用,$threadid 是另一个包含...threadid 的数组,并且循环正确地一个接一个地获取它们,这不是问题所在。

提前致谢!

最佳答案

您正在执行 O(N) 数据库查询,请考虑在您的 where 子句中使用 IN 表达式仅执行 O(1)。无需 foreach 循环,您将在一个数组中获取所有数据。

SELECT ... FROM Messages WHERE threadid IN (1, 2, 3, ...) AND ...

您可能必须为此使用准备好的语句。

关于php - 如何将元素添加到 php 数组而不显示为新数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41324214/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com