下面代碼的用意是從mysql表中提取消息,並將每個消息放在每個輸出周圍帶有{}的一個數組中。如您所見,每個輸出都由各種參數組成,並且本身就是一個數組。 代碼的作用是每次處理循環時,在後面的JSON數組中將其轉換爲,它將輸出包裝在[]中,因此它現在是一個新創建的數組。 我得到的是:如何將元素添加到php數組而不顯示爲新數組
[{"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;
}
,僅供參考,$線程ID是一個包含另一個數組...線程ID,並且循環正確獲取這些一個接一個,that's問題並不在那裏。
在此先感謝!
* ...並將它們中的每一個放在每個輸出周圍的一個數組中{},您是否試圖獲取json字符串? –
你能指定你的意思嗎?「在每個輸出周圍用{}排列一個陣列」_?你在哪裏/如何看待這些括號?作爲Json也許?由於{}表示一個對象,而不是一個數組,所以你想要的東西有點混亂。 – Jeff
您需要在foreach之外定義空數組var,並將數組內容推送到foreach中。 – Eugen