简体   繁体   中英

building a multi dimentional array from mysqli database query using php

I am trying to build a multi dimentional 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,
        )
)

the number being the members id followed by their data.

So i have 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 this isnt producing the correct results, so im guessing my array building sucks :( here is what i am getting.

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

Could someone help me please to build a successful multi dimentional array from the data im my database

Many Thanks

You need a second level when you create the array, instead of just simply adding keys and data to the array.

So, first create an index (key) with the student ID, then the value of that new index will be a sub-array with all the data for that student.
Then next loop it 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,
        );

    }
}

使用array结构:

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

You need to do in following manner--

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

Note:- if condition is not required because your array is created through id.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM