简体   繁体   中英

Build a PHP array from a MySQL table

I want to create array from multiple rows. In My table I have Year field, regd field for counting the number of students, and Class field. I want to output the data like below.

$data = array( 
              '2012' => array(
                             'KG_I' => 87,
                             'KG_II' => 80,
                             'I' => 90,
                             'II' => 120,
                             'III' => 100,
                             'IV' => 110,
                             'V' => 98,
             ),
             '2013' => array(
                             'KG_I' => 82,
                             'KG_II' => 84,
                             'I' => 92,
                             'II' => 110,
                             'III' => 120,
                             'IV' => 108,
                             'V' => 90,
             ),
            '2014' => array(
                            'KG_I' => 90,
                            'KG_II' => 83,
                            'I' => 95,
                            'II' => 110,
                            'III' => 120,
                            'IV' => 81,
                            'V' => 95,
            ),
  );

My attempt was like this:

$std=array();
$hms="SELECT COUNT(DISTINCT regd) as stdNum, Class, Year FROM 
      student GROUP by Class";
$quar=mysql_query($hms);
$myarray = array();
while($row = mysql_fetch_array($quar)){
    $myarray[$row['Class']] = $row['stdNum'];
}

I have no idea how I output the Year array.

Let's try this :

while($row = mysql_fetch_array($quar)){
    $myarray[$row['Year']][$row['Class']] = $row['stdNum'];
}

Enjoy :)

$std=array();
$hms="Select Year,Class,count(regd) 'stdNum' from       student group by Year,Class";
$quar=mysql_query($hms);
$myarray = array();
while($row = mysql_fetch_array($quar)){
    $myarray[$row['Year']]$row['Class']] =      $row['stdNum'];
}

You opened two arrays which is not necessary. print_r() may come handy when dealing with arrays. Hope this will help.

$hms="Select Year, Class, COUNT(DISTINCT regd) as stdNum 
      from student group by Year, Class";
$quar=mysql_query($hms);
$myArray = array();
while($row = mysql_fetch_assoc($quar)){
    $mya[$row['Year']][$row['Class']] =  $row['stdNum'];
}
echo "<pre>";
print_r($myArray);
echo "</pre>";

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