带有内容分组的PHP动态表

时间:2015-09-23 11:50:36

标签: php

我想做什么

我有一个看起来像这样的数组 -

Array
(
[0] => Array
    (
        [id] => 1
        [date] => 23-09-2015
        [name] => Public Transport
        [group_id] => 1
    )

[1] => Array
    (
        [id] => 2
        [date] => 23-09-2015
        [name] => Parking
        [group_id] => 1
    )

[2] => Array
    (
        [id] => 4
        [date] => 23-09-2015
        [name] => Food
        [group_id] => 2
    )

[3] => Array
    (
        [id] => 3
        [date] => 23-09-2015
        [name] => Fix
        [group_id] => 3
    )

[4] => Array
    (
        [id] => 4
        [date] => 23-09-2015
        [name] => Entertainment
        [group_id] => 3
    )

)

我想在表格中列出,并根据组ID

进行分组

该小组有交通[1],住宿[2]和津贴[3]。 [4]未分组。

表结构需要如下所示。

  ID| Date     | Name             |
  ---------------------------------
  ---------------------------------
  1 |23-09-2015|Public Transport
  2 |23-09-2015|Parking
  ---------------------------------
          TRANSPORTATION
  ---------------------------------
  3 |23-09-2015|Food
  ---------------------------------
          ACCOMMODATION
  ---------------------------------
  4 |23-09-2015|Fix
  ---------------------------------
          ALLOWANCE
  ---------------------------------
  5 |23-09-2015|Entertainment

正如你在这里看到的那样,id 1& 2个来自交通,3个住宿,4个住宿和娱乐没有团体。 如果任何组dosenot在数组中有数据,那么它应该显示NO DATA AVAILABLE

  ---------------------------------
  3 |23-09-2015|Food
  ---------------------------------
          ACCOMMODATION
  ---------------------------------
       No data available
  ---------------------------------
          ALLOWANCE
  ---------------------------------

我尝试了什么

     <?php
     $j = 1;
     foreach ($summary as $list) {
        if ($j != $list['group_id']) {

             if ($j == 1) {
                   $group = 'Transportation';
             } else if ($j == 2) {
                    $group = 'Accomodation';
              } else if ($j == 3) {
                    $group = 'Allowances';
              } else {
                    $group = '';
              }
          ?>

                        <tr class="summary-title">
                            <td colspan="7"><?php echo $group; ?></td>
                        </tr>
                    <?php } ?>
      <tr>

           <td><?php echo $list['id']; ?></td>
           <td><?php echo $list['date']; ?></td>
           <td><?php echo $list['name']; ?></td>
      </tr>
        <?php
            $j = $list['group_id'];
        }
        ?>

数组按照group_id的顺序排序。组ID将始终具有值1,2,3,4。

我的代码问题

部分工作。但是当group_id数组中没有值时,我无法显示NO DATA AVAILABLE。此外,如果group_id = 4在数组中不可用,那么它不会在底部设置ALLOWANCE,因为数组循环在设置值之前完成。

2 个答案:

答案 0 :(得分:0)

编辑:删除了整个页面,因为它现在变得混乱。

$summary = array();
$summary[] = array('id'=>1, 'date'=>"23-09-2915", 'name'=>"Public transpor1", 'group_id'=> 1);
$summary[] = array('id'=>2, 'date'=>"24-09-2915", 'name'=>"Public transpor2", 'group_id'=> 3);
$summary[] = array('id'=>3, 'date'=>"25-09-2915", 'name'=>"Public transpor3", 'group_id'=> 1);
$summary[] = array('id'=>4, 'date'=>"26-09-2915", 'name'=>"Public transpor4", 'group_id'=> 2);
$summary[] = array('id'=>5, 'date'=>"27-09-2915", 'name'=>"Public transpor5", 'group_id'=> 1);
$newarray = array('Transportation'=>array(),'Accomodation'=>array(),'Allowances'=>array(),'Not found'=>array());
foreach ($summary as $list) {
    if(isset($list['group_id'])){
         $testid = $list['group_id'];
    }else{
         $testid = 4;
    }
    if ($testid  == 1) {
        $group = 'Transportation';
    } else if ($testid  == 2) {
        $group = 'Accomodation';
    } else if ($testid  == 3) {
        $group = 'Allowances';
    } else {
        $group = 'Not found';
    }
    $newarray[$group][] = $list;
}
echo "<table>";
foreach($newarray as $key => $array){
    echo "<tr><th>".$key."</th></tr>";
    if(count($array) > 0){
        foreach($array as $row){
            echo "<tr><td>".$row['name']."</td></tr>";
        }
    }else{
        echo "<tr><td>Not data</td></tr>";
    }
}
echo "</table>";

这应该做你现在想要的但是认真,付出一些努力lol。如果您对问题不太清楚,我将不会继续编辑它,直到它完成您想要的内容

答案 1 :(得分:0)

希望这对你有所帮助。这是一个小例子。

转储:

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET NAMES utf8 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;

CREATE DATABASE IF NOT EXISTS `my` /*!40100 DEFAULT CHARACTER SET utf8 */;
USE `my`;


CREATE TABLE IF NOT EXISTS `category` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL,
  `group_id` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `name` (`name`),
  KEY `FK_category_category_group` (`group_id`),
  CONSTRAINT `FK_category_category_group` FOREIGN KEY (`group_id`) REFERENCES `category_group` (`id`) ON DELETE SET NULL ON UPDATE SET NULL
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8;

/*!40000 ALTER TABLE `category` DISABLE KEYS */;
INSERT INTO `category` (`id`, `name`, `group_id`) VALUES
    (1, 'Public Transport', 1),
    (2, 'Parking', 1),
    (3, 'Food', 2),
    (4, 'Fix', 3),
    (5, 'Entertainment', 3),
    (6, 'Category without group 1', NULL),
    (7, 'Category without group 2', NULL);
/*!40000 ALTER TABLE `category` ENABLE KEYS */;

CREATE TABLE IF NOT EXISTS `category_group` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `name` (`name`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;

/*!40000 ALTER TABLE `category_group` DISABLE KEYS */;
INSERT INTO `category_group` (`id`, `name`) VALUES
    (2, 'Accommodation '),
    (3, 'Allowance '),
    (1, 'TRANSPORTATION');
/*!40000 ALTER TABLE `category_group` ENABLE KEYS */;
/*!40101 SET SQL_MODE=IFNULL(@OLD_SQL_MODE, '') */;
/*!40014 SET FOREIGN_KEY_CHECKS=IF(@OLD_FOREIGN_KEY_CHECKS IS NULL, 1, @OLD_FOREIGN_KEY_CHECKS) */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;

PHP:

$categoriesByGroups = array();
$pdo = new PDO('mysql:host=localhost;dbname=my', 'root');
$query = $pdo->prepare('
    SELECT c.id AS category_id,
           c.name AS category_name,
           c.group_id,
           g.name AS group_name
      FROM category AS c
      LEFT JOIN category_group AS g ON g.id = c.group_id
');

$query->execute();

while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
    if ($row['group_id'] != null) {
        $groupId = $row['group_id'];
    } else {
        $groupId = 0;
    }

    if (!isset($categoriesByGroups[$groupId])) {
        $categoriesByGroups[$groupId] = array(
            'categories' => array(),
            'group' => $groupId == null ? 'Without group' : $row['group_name']
        );
    }

    $categoriesByGroups[$groupId]['categories'][] = $row['category_name'];
}

foreach ($categoriesByGroups as $group) {
    echo 'Group: ' . $group['group'] . '<br/>';
    echo 'Categories: <br/>';
    foreach ($group['categories'] as $category) {
        echo $category . '<br/>';
    }
    echo '--------------------------------<br/>';
}