爲了解釋這一場景:添加MySQL的結果PHP數組有重複的值
我有這個表在MySQL數據庫
+-------------------------------------------------------------------------+
| message_id | client_id | admin_id | message | date_posted | read_status |
+-------------------------------------------------------------------------+
我選擇所有消息和一個二維數組中對其進行分組同一個客戶端,這樣的結果migh樣子
$messages = array(
"4" => array ("338", "4", "1", "message1", "20170904 120803", "0"),
"5" => array ("339", "5", "1", "message2", "20170904 120807","0")
);
我得到的是類似的,但在陣列中的每個值被複制
結果array (size=12)
'message_id' => string '22' (length=2)
0 => string '22' (length=2)
'client_id' => string '14' (length=2)
1 => string '14' (length=2)
'admin_id' => string '1' (length=1)
2 => string '1' (length=1)
'message' => string 'hii I'm new to this' (length=19)
3 => string 'hii I'm new to this' (length=19)
'date_posted' => string '2017-04-22 17:17:13' (length=19)
4 => string '2017-04-22 17:17:13' (length=19)
'read_status' => string '0' (length=1)
5 => string '0' (length=1)
這是我的查詢
$grouped_messages = array();
foreach ($connect->query("SELECT DISTINCT * FROM request ORDER BY client_id") as $row) {
var_dump($row);
$client_id = $row['client_id'];
if (!isset($grouped_messages[$client_id])) {
$grouped_messages[$client_id] = array();
}
$grouped_messages[$client_id][] = $row;
}
foreach ($grouped_messages as $client_id => $client_messages) {
echo '<div>';
echo '<p>Messages for client #' . $client_id . '</p>';
foreach ($client_messages as $message) {
foreach($message as $column) {
echo $column;
}
}
echo '</div>';
}
上這是爲什麼發生任何想法呢?
PS相同的客戶端可以有多個消息,這意味着這個表中的多行,這就是它將來自同一客戶端的所有消息放入關聯數組中的代碼!
請注意DISTINCT *是oxymoronic – Strawberry