Reputation: 305
To explain the scenario:
I have this table in MySQL DB
+-------------------------------------------------------------------------+
| message_id | client_id | admin_id | message | date_posted | read_status |
+-------------------------------------------------------------------------+
I am selecting all the messages and grouping them in a 2D Array for the same client so that the result migh look like
$messages = array(
"4" => array ("338", "4", "1", "message1", "20170904 120803", "0"),
"5" => array ("339", "5", "1", "message2", "20170904 120807","0")
);
The result I'm getting is similar but each value in the array is duplicated
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)
This is my query
$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>';
}
Any Ideas on why that is happening?
PS The same client can have multiple messages meaning multiple rows in this table that's what the code it puts all those messages from the same client into the associative array!
Upvotes: 1
Views: 563
Reputation: 54841
Fetching both numeric and text keys is a default behaviour of PDO fetch.
You can change it, in your case this should be done by setting attribute PDO::ATTR_DEFAULT_FETCH_MODE
to PDO::FETCH_ASSOC
:
$connect->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
Or you can do it when you instantiate new PDO object.
More modes here.
Upvotes: 2