将数组解析为HTML结构的最有效方法

时间:2013-09-12 14:34:33

标签: php html arrays loops for-loop

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

$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'];
}
?>

3 个答案:

答案 0 :(得分: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";
}

希望这很简单。

答案 1 :(得分: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>';
    }
}

答案 2 :(得分: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循环循环。