简体   繁体   English

使用php从mysqli数据库查询构建多维数组

[英]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. 我正在尝试使用mysqli和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. 数字是成员ID,后跟数据。

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. 因此,首先使用学生ID创建索引(键) ,然后该新索引将是包含该学生的所有数据的子数组。
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. 注意: - 如果不需要条件,因为您的数组是通过id创建的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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