Reputation: 13
I am trying to convert the results from a MySQLi select to a multidimensional array but am not getting the desired result. This is the data returned from the SELECT statement:
+----+------------+
| id | value |
+----+------------+
| 2 | Red |
| 2 | Blue |
| 1 | Green |
| 1 | Yellow |
| 1 | Orange |
| 3 | Teal |
+----+------------+
There can be multiple values with the same id. My fetch statement looks like this:
while ($stmt->fetch()) {
$colors[] = array($value);
}
The result looks like this:
Array
(
[0] => Array
(
[0] => Red
)
[1] => Array
(
[0] => Blue
)
[2] => Array
(
[0] => Green
)
[3] => Array
(
[0] => Yellow
)
[4] => Array
(
[0] => Orange
)
[5] => Array
(
[0] => Teal
)
)
However, want I really want is the array to look like this:
Array
(
[0] => Array
(
[0] => Red
[1] => Blue
)
[1] => Array
(
[0] => Green
[1] => Yellow
[2] => Orange
)
[2] => Array
(
[0] => Teal
)
)
Any help would be appreciated!
Upvotes: 1
Views: 273
Reputation: 41885
Alternatively, you could use the id to group them inside the loop. Example:
$stmt->bind_result($id, $value);
while ($stmt->fetch()) {
$colors[$id][] = $value;
}
// $colors = array_values($colors); // optional, if you want to reindex the keys
Upvotes: 2