简体   繁体   English

带有内容分组的PHP动态表

[英]PHP Dynamic table with content grouping

What I am trying to do 我想做什么

I have an array which looks like this - 我有一个看起来像这样的数组 -

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
    )

)

I want to list it in table with grouping done according to the group id 我想在表中列出它,根据组ID完成分组

The group has Transportation [1], Accommodation [2] and Allowance [3]. 该集团有交通运输[1],住宿[2]和津贴[3]。 [4] is ungrouped. [4]未分组。

The table structure need to look as shown below. 表结构需要如下所示。

  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

As you can see here id 1 & 2 comes under Transportation, 3 comes under accommodation, 4 comes under allowance and entertainment does not have group. 正如你在这里看到的那样,id 1和2属于Transportation,3个属于住宿,4个属于免税区,娱乐区没有小组。 If any group dosenot have data in the array then it should show NO DATA AVAILABLE 如果任何组dosenot在数组中有数据,那么它应该显示NO DATA AVAILABLE

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

What I tried 我尝试了什么

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

The array is ordered according with group_id as ascending. 数组按group_id按升序排序。 Group id will have values 1, 2, 3, 4 always. 组ID将始终具有值1,2,3,4。

Problem with my code 我的代码有问题

It works partially. 它部分工作。 But I am unable to show NO DATA AVAILABLE when there's no value in array with the group_id. 但是当group_id数组中没有值时,我无法显示NO DATA AVAILABLE。 Also if group_id = 4 is not available in array then it doesnot set ALLOWANCE at the bottom as the array loop finishes before the value is set. 此外,如果group_id = 4在数组中不可用,那么它不会在底部设置ALLOWANCE,因为数组循环在设置值之前完成。

EDIT: Removed the whole page because its getting to chaotic right now. 编辑:删除了整个页面,因为它现在变得混乱。

$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>";

This should do what you want now but seriously, put some effort into it lol. 这应该做你想要的,但是认真的,付出一些努力lol。 I'm not going to continue to edit it until it does what you want if you're so unclear with your questions 如果您对问题不太清楚,我将不会继续编辑它,直到它完成您想要的操作

Hope this help you. 希望这对你有所帮助。 Here a small example. 这是一个小例子。

Dump: 倾倒:

/*!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: 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/>';
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM