-1

我在PHP中有一个多维数组,如下所示:

Array
(
    [0] => Array
        (
            [category_id] => 1
            [name] => Football Team Name 1
        )
    [1] => Array
        (
            [category_id] => 2
            [name] => Football Team Name 2
        )
    [2] => Array
        (
            [category_id] => 3
            [name] => Hockey Team Name 1
        )
    [3] => Array
        (
            [category_id] => 4
            [name] => Hockey Team Name 2
        )
    [4] => Array
        (
            [category_id] => 5
            [name] => Hockey Team Name 3
        )

第一个单词(称为name的数组键)我总是用作类别标题,因此,我想但到目前为止无法弄清楚如何使最终输出看起来像这样:

输出示例

就我而言,该解决方案最终应与Smarty一起使用。

如果有任何想法,我将不胜感激。

4

1 回答 1

4

您应该在将数据解析给 Smarty 之前准备好数据。

你可以这样做:

$result = array(
    array('name' => 'Hockey Team 1', 'category_id' => 1),
    array('name' => 'Hockey Team 2', 'category_id' => 2),
    array('name' => 'Hockey Team 3', 'category_id' => 3),
    array('name' => 'Football Team 1', 'category_id' => 4),
    array('name' => 'Football Team 2', 'category_id' => 5),
    array('name' => 'Football Team 3', 'category_id' => 6)
);

$sports = array();

foreach ($result as $team) {
    $sport_parts = explode(' ', $team['name']);
    $sport = array_shift($sport_part);
    $team['name'] = join(' ', $sport_parts);
    if (isset($sports[$sport]) === FALSE) {
        $sports[$sport] = array();
    }
    $sports[$sport][] = $team;
}

这将产生一个像这样的数据集,在 Smarty 中很容易迭代:

array(2) {
  ["Hockey"]=>
  array(3) {
    [0]=>
    array(2) {
      ["name"]=>
      string(13) "Team 1"
      ["category_id"]=>
      int(1)
    }
    [1]=>
    array(2) {
      ["name"]=>
      string(13) "Team 2"
      ["category_id"]=>
      int(2)
    }
    [2]=>
    array(2) {
      ["name"]=>
      string(13) "Team 3"
      ["category_id"]=>
      int(3)
    }
  }
  ["Football"]=>
  array(3) {
    [0]=>
    array(2) {
      ["name"]=>
      string(15) "Team 1"
      ["category_id"]=>
      int(4)
    }
    [1]=>
    array(2) {
      ["name"]=>
      string(15) "Team 2"
      ["category_id"]=>
      int(5)
    }
    [2]=>
    array(2) {
      ["name"]=>
      string(15) "Team 3"
      ["category_id"]=>
      int(6)
    }
  }
}

Smarty 模板的示例:

{foreach from=$sports key=sport item=teams}
  <h1>{$sport}</h1>
    <ul>
      {foreach from=$teams item=team}
        <li>{$team['name']}</li>
      {/foreach}    
    </ul>
{/foreach}
于 2012-08-29T15:14:19.243 回答