对MySQL结果数组进行分类

时间:2013-05-25 18:34:28

标签: php arrays foreach

我有一个返回数据库结果的函数:

<?php print_r($homepagematches; ?> 
Array
(
[0] => Array
    (
        [matchid] => 30
        [matchtitle] => Testing This!
        [matchaverage] => 1
        [matchyoutubecode] => New Match
        [casterid] => 1
        [matchtype] => 
        [matchdate] => 2013-05-24 02:19:49
        [matchcasteryoutube] => http://youtube.com/huskystarcraft
        [matchcaster] => HuskyStarcraft
    )

[1] => Array
    (
        [matchid] => 27
        [matchtitle] => Psy vs Camara
        [matchaverage] => 1
        [matchyoutubecode] => nefC9vkMfG8
        [casterid] => 1
        [matchtype] => 
        [matchdate] => 2013-05-24 02:13:10
        [matchcasteryoutube] => http://youtube.com/huskystarcraft
        [matchcaster] => HuskyStarcraft
    )

该函数返回过去3天内的所有匹配项,我想弄清楚的是如何改进数组,以便我可以在发布它们的当天显示匹配项。我知道可能需要一个foreach循环,我只是无法理解我需要实现的概念。

$matchdate = '';
 foreach($this->data['homepagematches'] as $match){
    if($matchdate != date('m/d', strtotime($match['matchdate'])) || $matchdate == ''){
    $homematch[date('m/d', strtotime($match['matchdate']))] = array(
    "matchtitle" => $match['matchtitle']);
    }

基本上我需要Array看起来像:

Array 
(
[05/24] => Array
        (
              [matchid] =>30
              [matchtitle] => Testing This!
              [matchyoutubecode] => New Match
              [casterid] = 1
         )
 )

2 个答案:

答案 0 :(得分:0)

<?php
$MatchesByDate = array();
foreach($homepagematches as $match) {
    list($matchdate,$time) = explode(" ",$match["matchdate"]); //split field into date and time
    if( !isset($MatchesByDate[$matchdate]) )
         $MatchesByDate[$matchdate] = array(); // If the array for that date doesnt exist yet make it
    $MatchesByDate[$matchdate][] = $match; //Use the matchdate as a key and add to the array
}

答案 1 :(得分:0)

我认为应该这样做。

foreach($this->data['homepagematches'] as $match){
    $tag = date('m/d', strtotime($match['matchdate']));
    $data[$tag][] = array(
        "matchid" => $match['matchid'],
        "matchtitle" => $match['matchtitle'],
        "matchyoutubecode" => $match['matchyoutubecode'],
        "casterid" => $match['casterid']
    );
}
print_r($data);