【问题标题】:Using foreach() with a multidimensional array将 foreach() 与多维数组一起使用
【发布时间】:2014-03-06 03:18:09
【问题描述】:

我有一个 mySQL 表,可以简化成这样:

animal      breed
Cat         Persian
Cat         Siamese
Dog         Alsatian
Dog         Poodle

我想以这种形式显示信息:

<table>
<tr>
<td class="heading">Cat</td>
</tr>
<tr>
<td class="body">Persian</td>
<td class="body">Siamese</td>
</tr>
<tr>
<td class="heading">Dog</td>
</tr>
<tr>
<td class="body">Alsatian</td>
<td class="body">Poodle</td>
</tr>
</table>

到目前为止,我有一个这样的查询:

$query = "SELECT * FROM aa_animal";
$result = mysql_query($query, $MySQL_extranet) or die(mysql_error());
while($row = mysql_fetch_assoc($result)){
    $resultarray[] = $row;
}

然后我想我需要一对嵌套的 foreach() 循环,但多维数组的处理让我绝望地迷失了方向。

foreach("unique_animal") {
  <tr>
    <td class-"heading">$animal</td>
  </tr>
  if ($animal=="unique_animal") {
    foreach("row") {
    <tr>
      <td class-"body">$breed</td>
    </tr>
  }
}

如何操作 $resultarray 以获得 $animal、$breed 等的正确值?

目前的进展

贾斯汀的回复提供了上述问题的解决方案。然而,现实生活中的页面在数据库表中有更多的列。这是我最初给出的简单示例和我正在尝试创建的页面之间的中间文件的代码。

<?php

$countryid='spain';

// MySQL query to select hotels and display all the hotel info
$query = "SELECT hid, hotel, pricefrom, place, region, country, picture, property, prop2, rooms, summary, lat, lng, zoomloc, breakfast, searchparam, specialoffer, biz_model, ta_rating, bc_rating FROM ex_hotel WHERE country LIKE '%$countryid%' AND showhide = 'show' ORDER BY orderr DESC";
$result = mysql_query($query, $MySQL_extranet) or die(mysql_error());
while($row = mysql_fetch_assoc($result)) {
   if (isset($resultarray[$row['region']])) {
      $resultarray[$row['region']][] = $row['hotel'];
   }else{
      $resultarray[$row['region']] = array($row['hotel']);
   }
}
ksort($resultarray);
?>

<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>

<body>
<table width="500" border="1" cellspacing=" 4" cellpadding="4">
<?php foreach($resultarray as $region => $hotel)
{
   echo '<tr><td colspan="2" style="background-color:#ddd">'.$region.'</td></tr>';

   foreach($hotel as $value) {
      echo '<tr><td width="250px">'.$value.'</td>';
   }
   foreach($hid as $value2) {
      echo '<td>'.$value2.'</td></tr>';
   }
}?>
</table>
</body>
</html>

mySQL 查询中的所有这些值都需要在表中使用,但是如何获取它们?

【问题讨论】:

标签: php mysql arrays multidimensional-array foreach


【解决方案1】:

在获取数据时应该对数据进行分组

while($row = mysql_fetch_assoc($result))
{
   if (isset($resultarray[$row['animal']]))
      $resultarray[$row['animal']][] = $row['breed'];
   else
      $resultarray[$row['animal']] = array($row['breed']);
}

然后,显示它

foreach($resultarray as $animal => $breed)
{
   echo '<tr><td class="heading">'.$animal.'</td></tr>';

   foreach($breed as $value)
      echo '<tr><td class="body">'.$value.'</td></tr>';
}

编辑: 如果您需要更多列,您需要做的是存储整行而不是一个项目:

while($row = mysql_fetch_assoc($result))
{
   if (isset($resultarray[$row['region']]))
      $resultarray[$row['region']][] = $row;
   else
      $resultarray[$row['region']] = array($row);
}

然后,您还可以获取这些行

foreach($resultarray as $region => $rows)
{
   echo '<tr><td class="heading">'.$region.'</td></tr>';

   // this way (display everything)
   foreach($rows as $row)
      foreach($row as $key => $value)
         echo '<tr><td class="body">'.$key.': '.$value.'</td></tr>';

   // or this way (if you want to display only specific item)
   foreach($rows as $row)
      echo '<tr><td class="body">Hotel: '.$row["hotel"].' / price: '.$row["pricefrom"].'</td></tr>';
}

【讨论】:

  • 太棒了!我只是复制并粘贴了贾斯汀的代码,甚至没有停下来理解它,而且它奏效了。谢谢,贾斯汀。现在我所要做的就是扩展逻辑以在我的真实页面上工作。
  • 不可避免地,我在尝试扩大规模时遇到了问题。实际上,表中大约有 10 或 15 列,而不仅仅是两列。我该如何处理它们?是否可以执行类似 foreach($resultarray as $animal => $breed, $legs, $fur) 之类的操作来从其他列创建变量?
  • 不像你说的那样。如果不知道其他列的实用性以及您想用它们做什么,很难即时给您答案
  • 我将使用当前的测试文件更新我的原始问题。
  • 这里说我应该避免像“谢谢”这样的 cmets,但我还能说什么。非常感谢贾斯汀。希望这能教会我足够多的关于数组的知识,以便将来能够将它们应用于其他事物。
猜你喜欢
  • 1970-01-01
  • 2016-12-20
  • 1970-01-01
  • 2016-04-11
  • 2012-12-13
  • 2013-01-09
  • 1970-01-01
  • 2021-12-14
  • 1970-01-01
相关资源
最近更新 更多