如何从While循环生成多维数组?

时间:2013-04-19 07:03:09

标签: php mysql

我有这个功能:

function userKids(mysqli $Con, $Parent) {
    $stmt = $Con->prepare('SELECT KidsName, KidsAge, KidsGender FROM Kids WHERE Parent = ?');
    $stmt->bind_param('s', $Username);
    $stmt->execute();

    $Kid = null;
    $Kids = array();
    $stmt->bind_result($Kid, $KidsAge, $KidsGender);
    while($stmt->fetch()) {
        $Kids[] = $Kid;
    }
    return $Kids;
}

目前我的WHILE循环生成这样的数组:

Array ( [0] => john [1] => jane )

现在,如何制作多维数组,这样我就可以得到年龄和性别,如下所示:

Array
(
[john] => Array
  (
  [0] => 3
  [1] => male
  )
[jane] => Array
  (
  [0] => 2
  [1] => female
  )
)

3 个答案:

答案 0 :(得分:4)

更改行:

$Kids[] = $Kid;

要:

$Kids[$Kid] = array($KidsAge, $KidsGender);

答案 1 :(得分:1)

我建议您也为第二维使用关联数组。所以:

$Kids[$Kid] = array('age' => $KidsAge, 'gender' => $KidsGender);

答案 2 :(得分:1)

用以下代码替换代码的结尾:

$stmt->bind_result($KidName, $KidAge, $KidGender);
while($stmt->fetch()) {
    $Kids[$KidName] = array($KidAge,$KidGender);
}
return $Kids;