Creating multidimensional array from mysqli database query using php

I am trying to create a multidimensional array of students and their data from my database table using mysqli and php.

I want my array to look something like this.

Array #$adult array
(
    [626] => Array #student no 626 data
        (
            [name] => emily,
            [age] => 43,
            [height] => 156,
        )
    [627] =>   #student no 627 data
        (
            [name] => luke,
            [age] => 31,
            [height] => 176,
        )
)

      

a number that identifies the members, followed by their data.

So, I tried the following

$sql = "SELECT * FROM pzgym_waitinglist WHERE seen = 0 GROUP BY gym_discipline, school_yr, id";
$result = $db->query($sql);

if ($result->num_rows > 0)
{
    #set up array
    $adult = array();

    while($row = $result->fetch_array()) 
    {
        $id = $row["id"];
        $name = $row["name"];
        $age= $row["age"];
        $height = $row['height'];

        if($row['gym_discipline'] == "Adult Gymnastics")
        {
            $adult[$id] = "['name'] => $name, ['age'] => $age, ['height'] => $height";

        }
    }
}

      

but that doesn't give the correct results, so I'm guessing my array construction sucks :( Here's what I get.

Array
(
    [626] => ['name'] => Emily, ['age'] => 43, ['height'] => 156
    [627] => ['name'] => Luke, ['age'] => 31, ['height'] => 176
)

      

Can anyone help me to create a successful multidimensional array from data im my database

Many thanks

+3


source to share


3 answers


You need a second level when creating an array, not just adding keys and data to the array.

So, first create an index (key) with the student id, then the value of this new index will be a sub-array with all the data for that student.
Then in the next cycle, he will do the same for the next student.



Something like:

while($row = $result->fetch_array()) 
{
    $id = $row["id"];
    $name = $row["name"];
    $age= $row["age"];
    $height = $row['height'];

    if($row['gym_discipline'] == "Adult Gymnastics")
    {
        $adult[$id] = array(
           "name" => $name, 
            "age" => $age, 
            "height" => $height,
        );

    }
}

      

+3


source


Use the construction array

:



$adult[$id] = array('name' => $name, 'age' => $age, 'height' => $height);

      

+2


source


You need to do the following:

$adult[$id]['name'] = $name;
$adult[$id]['age'] = $age;
$adult[$id]['name'] = $height; 

      

Note: - if the condition is not required, because your array is created using an id.

+2


source







All Articles