开发者

How to get an array like the following from mysql through php?

开发者 https://www.devze.com 2023-03-30 19:37 出处:网络
I have a table like this- event (id,name,date) I need a result set like this $result = array( \'1\'=>array(

I have a table like this-

event (id,name,date)

I need a result set like this

$result = array(
    '1'=>array(
        array('id'=>2,'name'=>'foolball match','date'=>'2011-01-23'),
        array('id'=>5,'name'=>'cricket match','date'=>'2011-01-27')
    ),
    '3'=>array(
        array('id'=>11,'name'=>'100 m run','date'=>'2011-03-12'),
        array('id'=>27,'name'=>'Basket Ball','date'=>'2011-03-20'),
        array('id'=>43,'name'=>'foolball match','date'=>'20开发者_运维百科11-03-29')
    )
);

Here array keys (1,3) represents months (jan,mar). Events will be stored under these month number key. Here 2 is missing because there are no events in februry.

Can anybody please help me?


Try this

$result = array();
$year = 2011;
$query = 'SELECT `id`, `name`, `date`, EXTRACT(MONTH FROM `date`) AS `month` FROM `event` WHERE EXTRACT(YEAR FROM `date`) = "' . $year . '" ORDER BY `date` DESC';
$res = mysql_query($query);
while ($row = mysql_fetch_assoc($res)) {
  $result[$row['month']][] = $row;
}


After fetching the data, loop through the result set in PHP, processing the date values.


//assuming events are in this format
$events = array(
    array('id'=>2,'name'=>'foolball match','date'=>'2011-01-23'),
    array('id'=>5,'name'=>'cricket match','date'=>'2011-01-27'),
    array('id'=>11,'name'=>'100 m run','date'=>'2011-03-12'),
    array('id'=>27,'name'=>'Basket Ball','date'=>'2011-03-20'),
    array('id'=>43,'name'=>'foolball match','date'=>'2011-03-29')
);

$result = array();
foreach ($events as $event) {
    $month = (int)date('m', strtotime($event['date']));
    $result[$month][] = $event;
}
var_dump($result);
0

精彩评论

暂无评论...
验证码 换一张
取 消