1

为了简单起见,假设我有以下数组:

$a = array();
$a[0]['lab'] = 1;
$a[0]['name'] = 'test1';
$a[1]['lab'] = 1;
$a[1]['name'] = 'test2';
$a[2]['lab'] = 2;
$a[2]['name'] = 'test3';
$a[3]['lab'] = 2;
$a[3]['name'] = "test4";
$a[4]['lab'] = 2;
$a[4]['name'] = "test5";

请记住,该数组的长度是完全可变的,并且与每个实验室相关联的项目数量也可能会有所不同。每个实验室可能有一个,可能有 100 个。

我想要的 HTML 结构如下:

<div class="parent"> <!-- Records for lab == 1 -->
  <div class="child">test1</div>
  <div class="child">test2</div>
</div>
<div class="parent"> <!-- Records for lab == 2 -->
  <div class="child">test3</div>
  <div class="child">test4</div>
  <div class="child">test5</div>
</div>

我目前有一个带有一堆额外逻辑的 for 循环,这很丑陋/效率低下,偶尔会错过最后一个“父”div 的结束标记。我知道有一种更优雅的方法可以做到这一点,我很想看看其他人想出了什么。

** 编辑:

这是我现在的逻辑,它实际上适用于我抛出的测试用例,但它看起来很糟糕:

<?php
$labId = 0;
for($i = 0; $i < count(a); $i++)
{
  if(($i+1) < count($a)) { $j = $i + 1;}
  if($labId == 0 || $labId != $a[$i]['lab'])
  {
    echo '<div class="parent">';
  }
  echo '<div class="child">'.$a['name'].'</div>';
  if(($a[$j]['lab'] != $labId && $a[$i]['lab'] != $labId && $labId != 0) || count($a) == 1)
  {
    echo '</div>';
  }
  $labId = $a[$i]['lab'];
}
?>
4

3 回答 3

1

我会这样做:

$a = ... // copied from your code
$newArray = array();

foreach($a as $e){
    $newArray[$e['lab']][] = $e['name'];
}

foreach($newArray as $lab){
    echo "<div class=\"parent\">\n";
    foreach($lab as $child){
        echo "\t<div class=\"child\">".$child."</div>\n";
    }
    echo "</div>\n";
}

希望这很简单。

于 2013-09-12T15:02:46.727 回答
1

下面的代码应该可以在不创建新数组的情况下解决问题

foreach ($a as $key0 => $labs) {
    foreach ($labs as $key1 => $value) {
        if ($key1 == 'lab') {
            echo '<div class="parent">';
        } else {
            echo '<div class="child">'.$value.'</div>';
        }
    }

    //Close parent divs
    if (isset($key0['lab'])) {
        echo '</div>';
    }
}
于 2013-09-12T15:38:54.863 回答
0

我的解决方案在某种程度上是响应和其他一些尝试和错误的组合。

<?php
  // define original test array

  $a = array();
  $a[0]['lab'] = 1;
  $a[0]['name'] = 'test1';
  $a[1]['lab'] = 1;
  $a[1]['name'] = 'test2';
  $a[2]['lab'] = 2;
  $a[2]['name'] = 'test3';
  $a[3]['lab'] = 2;
  $a[3]['name'] = "test4";
  $a[4]['lab'] = 2;
  $a[4]['name'] = "test5";

  // new array has to be defined outside the foreach() loop, or it will be treated as a local var

  $anew = array();

  // for each entry, assign to $anew[lab#][next_avail_entry#]['name'] = <value>

  foreach ($a as $arec)
    $anew[$arec['lab']][]['name'] = $arec['name'];

  // output: one parent div for each lab, plus subdivs for as many values as are avail for each lab

  foreach ($anew as $alab)
  {
    printf("<div class=\"parent\">\n");
    foreach ($alab as $arec)
      printf("  <div class=\"child\">%s</div>\n", $arec['name']);
    printf("</div>\n");
  }
?>

*编辑:我发现的另一种解决方案是分别查询实验室和项目,并将实验室作为外部循环循环,将项目作为内部 foreach 循环。

于 2013-09-13T12:35:01.930 回答