使用数组创建多维数组并通过mysql表循环

时间:2015-06-29 14:44:23

标签: php mysql arrays multidimensional-array

我有一个具有以下结构的表。目前有9名学生参加了3个班级(01,16和52班),每个班级有3名学生。

studentcode | classcode  
-------------------------
D3kcIvyp    | 01  
DdIhBc      | 01  
2vx0KV      | 01  
9p1PxWCV    | 52  
RnmfH1WE    | 52  
MSTBEv      | 52  
Yp4J3o      | 16  
fWQ5Oo      | 16  
6sxw3u      | 16  

这是包含所有当前类的数组:

$classes_array = array ( [0] => 01 [1] => 52 [2] => 16 )

使用这个数组我想通过mysql表创建一个多维数组,其中类代码用作第一级键:

Array
(
    [01] => Array
        (
            [0] => D3kcIvyp
            [1] => DdIhBc
            [2] => 2vx0KV
        )

    [52] => Array
        (
            [0] => 9p1PxWCV
            [1] => RnmfH1WE
            [2] => MSTBEv
        )

    [16] => Array
        (
            [0] => Yp4J3o
            [1] => fWQ5Oo
            [2] => 6sxw3u
        )
)


foreach ($classes_array as $key => $value)
{

    $sql = "SELECT studentcode FROM table WHERE classcode = '$classes_array[$key]'";
    $result = mysql_query($sql) or die();
    while($data = mysql_fetch_array($result))
    {
        $studentcodes_array[] = $data['studentcode'];
    }

    foreach ($studentcodes_array as $studentcodeskey => $studentcodesvalue)
    {
        $multid_array[$value][] = $studentcodesvalue;
    }
}

使用上面的代码,遗憾的是我没有得到我想要的数组。我得到了这个:

Array
(
    [01] => Array
        (
            [0] => D3kcIvyp
            [1] => DdIhBc
            [2] => 2vx0KV
        )

    [52] => Array
        (
            [0] => D3kcIvyp
            [1] => DdIhBc
            [2] => 2vx0KV
            [3] => 9p1PxWCV
            [4] => RnmfH1WE
            [5] => MSTBEv
        )

    [16] => Array
        (
            [0] => D3kcIvyp
            [1] => DdIhBc
            [2] => 2vx0KV
            [3] => 9p1PxWCV
            [4] => RnmfH1WE
            [5] => MSTBEv
            [6] => Yp4J3o
            [7] => fWQ5Oo
            [8] => 6sxw3u
        )

)

我的代码出了什么问题?有人可以帮我吗?

1 个答案:

答案 0 :(得分:0)

您永远不会初始化$studentcodes_array,因此它会记住您之前循环中的所有值。

尝试在$studentcodes_array = array();之前添加while