PHP循环数组并在数组项

时间:2016-08-22 22:16:41

标签: php arrays for-loop foreach while-loop

我似乎已经多次得到这个问题然后弄清楚,然后在下次遇到它时我无法弄明白。

所以我有一个SQL语句,像往常一样返回$ result变量......

$result = $stmt->fetchAll( PDO::FETCH_ASSOC );

我会告诉你一个精简的回报

Array
(
    [eid] => 1
    [eTitle] => premier league
    [eDesc] => 
    [cid] => 1
    [deleted] => 0
    [eStartTime] => 15:00
    [eHome] => 1
    [eAway] => 2
    [eKickoff] => 15:00:00
    [eDate] => 2016-08-20
)
Array
(
    [eid] => 2
    [eTitle] => fa cup
    [eDesc] => 
    [cid] => 1
    [deleted] => 0
    [eStartTime] => 15:00
    [eHome] => 1
    [eAway] => 2
    [eKickoff] => 15:00:00
    [eDate] => 2016-08-27
)

现在我要做的是循环遍历$ result并在每个键eHome和eAway上运行下面的函数是我想要做的伪代码。

loop ( $reult ) 

$row[eHome][eHomeData] = $this->getTeam( $row['eHome'] )
$row[eHome][eAwayData] = $this->getTeam( $row['eAway'] )

所以基本上我想用家庭或团队数据重建数组,这些数据使用eHome和eAway中给出的id。

我应该这样做,还是应该在MySQL中使用JOINS?

对不起,如果我措辞严重,我已经挣扎了几个小时,并放弃了。

先谢谢你们。

汤姆

1 个答案:

答案 0 :(得分:0)

这就是我最后使用的那些人,对于措辞不好的问题感到抱歉。有没有更好的方法来执行此操作,这里是代码,然后是print_r()转储,以便您了解我的目标。

$stmt = $this->conn->prepare('
  SELECT * from events WHERE cid = :cid
');

$stmt->bindParam( ':cid', $categoryid, PDO::PARAM_INT );

if( $stmt->execute() )
{
    $result = $stmt->fetchAll( PDO::FETCH_ASSOC );

    $resultCount = count($result);

    for( $i = 0; $i < $resultCount; $i++ ) {

        $result[$i]['homeTeamData'] = $this->getTeam( $result[$i]['eHome'] );
        $result[$i]['awayTeamData'] = $this->getTeam( $result[$i]['eAway'] );
    }
}

下面是print_r(),它在上面添加的循环中添加了额外的awayTeamData和homeTeamData

Array
(
    [0] => Array
        (
            [eid] => 1
            [eTitle] => premier league
            [eDesc] => 
            [cid] => 1
            [deleted] => 0
            [eStartTime] => 15:00
            [eHome] => 1
            [eAway] => 2
            [eKickoff] => 15:00:00
            [eDate] => 2016-08-20
            [homeTeamData] => Array
                (
                    [tid] => 1
                    [tName] => Chelsea
                    [deleted] => 0
                )

            [awayTeamData] => Array
                (
                    [tid] => 2
                    [tName] => Man Utd
                    [deleted] => 0
                )

        )

    [1] => Array
        (
            [eid] => 2
            [eTitle] => fa cup
            [eDesc] => 
            [cid] => 1
            [deleted] => 0
            [eStartTime] => 15:00
            [eHome] => 1
            [eAway] => 2
            [eKickoff] => 15:00:00
            [eDate] => 2016-08-27
            [homeTeamData] => Array
                (
                    [tid] => 1
                    [tName] => Chelsea
                    [deleted] => 0
                )

            [awayTeamData] => Array
                (
                    [tid] => 2
                    [tName] => Man Utd
                    [deleted] => 0
                )

        )

)