mysql - Getting null array PHP -


i have database named "products" has column "categories". table contain 4 category of products namely electronic,decoration,clothes , vehicle. target show these category count ie:if there 4 products belongs category electronic, output should :electronic=4 , on

my code

    public function category()       {       $arraycategorys = ['electronic','decoration','clothes','vehicle'];       $data = [];       foreach($arraycategorys $arraycategory)        {       $sql = "select  count(id) products   categories='$arraycategory'";       $records = \db::select($sql);        $data = array_merge_recursive($data, [                    "{$arraycategory}" =>isset($records[0]->count),              ]);       $data=array_filter($data);       dd($data);       }  } 

i want show output

'electronic'=>'4',  'decoration'=>'2',  'clothes'=>'2', 

'vehicle'=>'1' according data in database iam getting nothing ,[]

you can group by categories way when count

select categories,count(*)   products  group categories;  

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

edit: though not familiar laravel5 syntax may work you

$result = db::table('products')             ->select('products.categories',                        db::raw('count(products.id) category_count')                     )             ->orderby('products.id', 'asc')             ->groupby('products.categories')             ->get(); 

Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -