【问题标题】:Show categories and then show sub-categories in php显示类别,然后在 php 中显示子类别
【发布时间】:2016-02-24 02:25:37
【问题描述】:

我好像被什么东西卡住了..

我正在尝试做的事情:使用以下示例数据,我尝试首先在类别中显示数据,然后在子类别中显示数据。

样本数据:

array('category'=> 'America',
'sub-category'=> 'Illinois',
'name'=>'John Doe');

array('category'=>'America',
'sub-category'=>'Wisconsin',
'name'=>'Jane Doe');

基本上是这样的:

America
  Illinois
    John Doe
  Wisconsin
    Jane Doe

我可以使用下面的代码来做分类:

   foreach ($total_states as $key => $states) {
     $states_category[$states['CATEGORY']]['category'] = $states['CATEGORY'];   
     $statest_category[$states['CATEGORY']]['name'][] = $states;    
   }

如何使用 for 循环按子类别对其进行分解?

【问题讨论】:

    标签: php arrays


    【解决方案1】:

    我测试并想出了这段代码:

    <?php
    $datas = [
        [
            'category' => 'America',
            'sub-category' => 'Illinois',
            'name' => 'John Doe'
        ],
        [
            'category' => 'America',
            'sub-category' => 'State',
            'name' => 'John Doedf'
        ],
        [
            'category' => 'America',
            'sub-category' => 'State',
            'name' => 'ghghjgj Doe'
        ],
    ];
    
    $newArray = [];
    
    foreach($datas as $d) 
        $newArray[$d['category']][$d['sub-category']][] = $d['name'];
    
    foreach($newArray as $country => $city) {
        echo $country. '<br>';
    
        foreach($city as $subcity => $users) {
            echo "\t $subcity <br>";
    
            foreach($users as $u)
                echo "\t\t $u <br>";
        }
    }
    

    【讨论】:

      【解决方案2】:

      试试这个:

      初始数据:

      $info = [
               ['category' => 'America',
                'sub-category' => 'Illinois',
                'name' => 'John Doe'],
              ['category' => 'America',
               'sub-category' => 'Wisconsin',
               'name' => 'Jane Doe']];
      

      Foreach:

              foreach ( $info as $array ){
                  foreach ( $array as $key => $value){
                      switch ( $key ){
                          case 'category' : {
                              echo $value . '<br>'; 
                              break;
                          }
                          case 'sub-category' : {
                              echo "&nbsp; " . $value . '<br>';
                              break;
                          }
                          case 'name' : {
                              echo "&nbsp; &nbsp; " . $value . '<br>';
                              break;
                          }
                      }
                  }
              }
      

      【讨论】:

        猜你喜欢
        • 2021-01-09
        • 2011-07-14
        • 1970-01-01
        • 2017-06-29
        • 2021-01-01
        • 2012-10-14
        • 2016-10-12
        • 2019-03-31
        • 1970-01-01
        相关资源
        最近更新 更多