Aloysia de Argenteuil
Aloysia de Argenteuil

Reputation: 902

How to direct create a multidimensional array from a mysql query using php?

How can I have directly a multidimensional array from following mysql query?

$query = SELECT * FROM table WHERE field1 = 1;

I've tried the following:

$result = mysqli_query($connection, $query);

while ($row = mysqli_fetch_array($result)){
    $table[] = ($row['field1'].'~'.$row['field2'].'~'.$row['field3'].'~'.$row['field4']);
}

If we print it we have following result:

array(
    [0] => 1 ~ ALFA  ~ beta   ~ 57
    [1] => 1 ~ BETA  ~ gamma  ~ 18
    [2] => 1 ~ GAMMA ~ delta  ~ 24
    ...
    [999] => 1 ~ ZETA ~ theta ~ 19
)

Then I have to explode it to have the multidimensional array that I wish:

foreach ($table as $value) {
    $tableWithSubArrays[] = explode("~", $value);
}

And then we got it:

Array(
    [0] => Array
        (
            [0] => 1
            [1] => ALFA
            [2] => beta
            [3] => 57
    )

    [1] => Array
        (
            [0] => 1
            [1] => BETA
            [2] => gamma
            [3] => 18
    )

    ...

    [999] => Array
        (
            [0] => 1
            [1] => ZETA
            [2] => theta
            [3] => 19
    )

Is there any other way that make it directly from the query to the multidimensional array?

Many thanks in advance!

Upvotes: 0

Views: 104

Answers (1)

Cheery
Cheery

Reputation: 16214

while ($row = mysqli_fetch_array($result)){
    $table[] = $row;
}

Upvotes: 1

Related Questions