简体   繁体   中英

How To Produce Multidimensional Array From While Loop?

I have this function :

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;
}

currently my WHILE loop produce array like this :

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

Now, how to produce multidimensional array so I can get the Age and Gender as well, like this :

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

Change the line:

$Kids[] = $Kid;

To:

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

I recommend that you use an associative array for the second dimension as well. So:

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

replace the end of your code by:

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

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