带有左连接的SQL查询结果和带有PHP的结果数组

时间:2012-03-27 01:00:01

标签: php sql arrays multidimensional-array left-join

我有以下查询:

SELECT * FROM teams
LEFT JOIN participants
ON teams.teamNo = participants.teamNo
ORDER BY teams.teamNo ASC

查询显然会获得团队表中的所有团队以及参与者表中返回的匹配参与者的位置。并非每个团队都可以分配参与者,但必须显示每个团队。

我想将数据显示在同一页面上(通知团队2没有当前参与者但仍然显示:

Team 1:    
 - Participant 1
 - Participant 2
 - Participant 3

Team 2:

Team 3:    
 - Participant 1
 - Participant 2

我目前从SQL查询中返回以下数组:

Array
(
[0] => Array
    (
        [TeamNo] => 1
        [ParticipantFirstNames] => Katie
        [ParticipantSurname] => Bloggs
    )

[1] => Array
    (
        [TeamNo] => 1
        [ParticipantFirstNames] => Jenny
        [ParticipantSurname] => Ruffles
    )

[2] => Array
    (
        [TeamNo] => 1
        [ParticipantFirstNames] => Hannah
        [ParticipantSurname] => Cox
    )

[3] => Array
    (
        [TeamNo] => 2
        [ParticipantFirstNames] => 
        [ParticipantSurname] => 
    )

[4] => Array
    (
        [TeamNo] => 3
        [ParticipantFirstNames] => Alex
        [ParticipantSurname] => Glover
    )

[5] => Array
    (
        [TeamNo] => 3
        [ParticipantFirstNames] => Karl
        [ParticipantSurname] => Lawrence
    )

我相信我需要将它转换为类似下面的数组,但我不确定如何在PHP中执行此操作:

array(
array(  'TeamNo' => '1',
        'TeamParticipants' => array(
                            array(  'ParticipantFirstName' => 'Harry',
                                    'ParticipantSurname' => 'Bloggs'),
                            array(  'ParticipantFirstName' => 'James',
                                    'ParticipantSurname' => 'Car'))
                            )

array(  'TeamNo' => '2',
        'TeamParticipants' => array() )


array(  'TeamNo' => '3',
        'TeamParticipants' => array(
                            array(  'ParticipantFirstName' => 'Harry',
                                    'ParticipantSurname' => 'Bloggs'),
                            array(  'ParticipantFirstName' => 'James',
                                    'ParticipantSurname' => 'Car')
                                )

                            )
)

我无法理解数组可以有人帮忙,还是我首先需要一个不同的查询?我正在使用PHP。

3 个答案:

答案 0 :(得分:2)

这会将您当前的数组转换为您想要的数组:

$newArray = array();
foreach ($resultArray as $record) {
    $currentTeam = $record('TeamNo');
    if (!array_key_exists($currentTeam, $newArray)) {
        $newArray[$currentTeam] = array('TeamNo' => $currentTeam, 'TeamParticipants => array());
    }
    if (!empty($record['ParticipantFirstName']) {
        $newArray[$currentTeam]['TeamParticipants'][] = array('ParticipantFirstName' => $record['ParticipantFirstName'], 'ParticipantLastName' => $record['ParticipantLastName']);
    }
}

这在很大程度上是未经测试的,但它基本上应该提供你想要的东西。唯一的区别是我在外面使用一个关联数组来轻松查找已创建的团队编号。

我没有对你为什么希望这种方式改变数组做出任何判断。我假设你最了解为什么你想要这种格式的数组。这应该可以帮助你实现它。

答案 1 :(得分:0)

您是否尝试过mysql_fetch_assoc()或mysql_fetch_array()?你在获取输出时使用了什么功能

 $query = "SELECT * FROM teams
 LEFT JOIN participants
 ON teams.teamNo = participants.teamNo
 ORDER BY teams.teamNo ASC"

 $result = mysql_query($query);

 while($row = mysql_fetch_array($result)){
     echo $row[0];
     echo $row[1];
     //and so on, this will display the data starting by the index 0 which is the first field
 }

答案 2 :(得分:0)

这样的事情应该做:

$q=mysql_query("your query");
while($r=mysql_fetch_assoc($q)) {
  $a["Team ".$r["teamNo"]][]=array("fname"=>$r["firstName"], "sname"=>$r["surname"]);
}

$a["Team ".$r["teamNo"]]创建 - 或引用数组"Team N"的关联索引$a的现有值。

$a["Team ".$r["teamNo"]][]表示该值是一个自动递增的int-indexed数组(因此在每次调用时创建一个新的int键)。

我们将与此自动递增索引匹配的值设置为具有2个键/值对的数组:"fname"引用当前参与者的名字,"sname"引用他/她的姓氏。 这给出了结构:

$a : array {
  "Team 1" : array {
    0 : array {
      "fname" > "Billy"
      "sname" > "The Kid"
    }
  }
  "Team 1" : array {
    1 : array {
      "fname" > "John"
      "sname" > "Dillinger"
    }
  }
  "Team 2" : array {
    0 : array {
      "fname" > "Melvin"
      "sname" > "Purvis"
    }
  }

  "Team 2" : array {
    1 : array {
      "fname" > "Eliot"
      "sname" > "Ness"
    }
  }
}

使用PHP,您可以像访问它一样访问它:

$a["Team 1"][0]["fname"] //Billy
$a["Team 1"][1]["fname"] //John
$a["Team 1"][0]["sname"] //The Kid
$a["Team 2"][1]["sname"] //Ness

因此,例如使用循环进行显示:

foreach($a as $team=>$participants) {
  echo "<h1>$team</h1>";
  foreach($participants as $identity) { //no need for keys here, as they're semantically irrelevant
    echo $identity["fname"]." ".strtoupper($identity["sname"])."<br>";
  }
}

这将显示

<h1>Team 1</h1>
Billy THE KID<br>
John DILLINGER<br>
<h1>Team 2</h1>
Melvin PURVIS<br>
Eliot NESS<br>

希望这足以让您更好地理解数组。