获取null数组PHP

时间:2015-05-31 05:16:27

标签: php mysql arrays laravel

我有一个名为“products”的数据库,其中有一列“categories”。此表包含四类产品,即electronicDecorationclothesvehicle。我的目标是显示这些categorycounte: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' 但我什么都没得到,[]

2 个答案:

答案 0 :(得分:1)

GROUP BY

时,您可以COUNT这样的方式SELECT categories,COUNT(*) FROM products GROUP BY categories;
$result = DB::table('products')
            ->select('products.categories', 
                      DB::raw('count(products.id) as category_count')
                    )
            ->orderBy('products.id', 'asc')
            ->groupBy('products.categories')
            ->get();

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

编辑:虽然我不熟悉laravel5语法,但这可能适合你

OnGlobalLayoutListener

答案 1 :(得分:0)

您使用了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);
      }
 }