1

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!

1
  • Please, provide full select query. And fix your while loop. Commented Oct 10, 2014 at 4:38

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.