【问题标题】:Getting null array PHP获取空数组PHP
【发布时间】:2015-08-13 18:26:04
【问题描述】:

我有一个名为“products”的数据库,其中有一列“categories”。此表包含四类产品,即electronicDecorationclothesvehicle。我的目标是显示这些category 和他们的count ie:if there are four products belongs to category electronic, then output should be like this :electronic=4 等等

我的代码

    public function category()
      {
      $arrayCategorys = ['electronic','Decoration','clothes','vehicle'];
      $data = [];
      foreach($arrayCategorys as $arrayCategory)
       {
      $sql = "SELECT  count(id) FROM products WHERE   categories='$arrayCategory'";
      $records = \DB::select($sql); 
      $data = array_merge_recursive($data, [

                  "{$arrayCategory}" =>isset($records[0]->count),

            ]);
      $data=array_filter($data);
      dd($data);
      }
 }

我想显示这样的输出

'electronic'=>'4',

'Decoration'=>'2',

'clothes'=>'2',

'vehicle'=>'1'根据数据库中的数据 但我什么也没得到,[]

【问题讨论】:

    标签: php mysql arrays laravel


    【解决方案1】:

    当您COUNT时,您可以像这样GROUP BY您的类别

    SELECT categories,COUNT(*)  
    FROM products 
    GROUP BY categories; 
    

    创意: http://www.w3resource.com/mysql/aggregate-functions-and-grouping/aggregate-functions-and-grouping-count-with-group-by.php

    编辑:虽然我不熟悉 laravel5 语法,但这可能对你有用

    $result = DB::table('products')
                ->select('products.categories', 
                          DB::raw('count(products.id) as category_count')
                        )
                ->orderBy('products.id', 'asc')
                ->groupBy('products.categories')
                ->get();
    

    【讨论】:

    • 我如何在 laravel5 中使用查询生成器
    • @RanjitKarki 我已经更新了我的答案。让我知道它是否适合您?
    【解决方案2】:

    您使用了isset($records[0]->count),但计数的列名将是count(id)。将计数命名为count,例如"SELECT count(id) AS count FROM products WHERE categories='$arrayCategory'"。而且您将无法仅通过检查它是否已设置来获得计数。删除 isset 并使用 $records[0]->count。代码应如下所示:

     public function category()
     {
          $arrayCategorys = ['electronic','Decoration','clothes','vehicle'];
          $data = [];
          foreach($arrayCategorys as $arrayCategory)
           {
          $sql = "SELECT  count(id) AS count FROM products WHERE   categories='$arrayCategory'";
          $records = \DB::select($sql); 
          $data = array_merge_recursive($data, [
    
                      "{$arrayCategory}" =>$records[0]->count,
    
                ]);
          $data=array_filter($data);
          dd($data);
          }
     }
    

    【讨论】:

      猜你喜欢
      • 2012-06-24
      • 1970-01-01
      • 1970-01-01
      • 2023-04-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-01
      • 2018-04-08
      相关资源
      最近更新 更多