Sign up ×
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other. Join them; it only takes a minute:

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!

share|improve this question

1 Answer 1

up vote 1 down vote accepted
while ($row = mysqli_fetch_array($result)){
    $table[] = $row;
}
share|improve this answer
    
Wow! that was compact! :) Thank you, @Cheery!!! And what about if I would like to have just some values, let's say of key[1] and key[3]? – Aloysia de Argenteuil Oct 1 '14 at 3:28
    
@AloysiadeArgenteuil not sure what you are asking about. Do not want to put all the columns - do not request them from database. SELECT field2, field4 FROM table WHERE field1 = 1; – Cheery Oct 1 '14 at 3:32
    
Yeah, you're right, @Cheery, I wasn't clear... ;-) I still want to select everything from the database, but the array should have only some fields... array ( [0] => array ( [0] => ALFA [1] => 57 ) [1] => array ( [0] => BETA [1] => 18 ) etc.) – Aloysia de Argenteuil Oct 1 '14 at 3:39
1  
@AloysiadeArgenteuil loop and create a new array `while ($row = mysqli_fetch_array($result)){ $table[] = array($row['field1'], $row['field2']); } – Cheery Oct 1 '14 at 3:40

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.