php - count array value with condition -
i have array data contain values. want count particular key value.
my array :
array ( [0] => stdclass object ( [id] => 3 [product_id] => 42 [user_id] => 69 [order_item_id] => 0 [sku_id] => 78 [rate] => 4 // count [description] => wonderful dress. [is_certifiedbuyer] => 1 [status] => 1 [deleted] => 0 [created_at] => 2016-03-11 16:53:31 [updated_at] => 2016-03-11 16:53:31 [username] => hiral [productname] => aish dress ) [1] => stdclass object ( [id] => 4 [product_id] => 42 [user_id] => 12 [order_item_id] => 0 [sku_id] => 78 [rate] => 2 [description] => greate dress. [is_certifiedbuyer] => 1 [status] => 1 [deleted] => 0 [created_at] => 2016-03-11 16:53:31 [updated_at] => 2016-03-11 16:53:31 [username] => admin [productname] => aish dress ) )
from above array want count total 5 rated user, total 4 rated user, total 3 rated... etc
in short want count rate field above array.
i have tried :
$reviews=$this->productreviewrepo->productreview(42); $div1 = array_filter($reviews, function($review) { return substr('4', $review->rate) !== false; }); echo '<pre>';print_r(count($div1)); $div2 = array_filter($reviews, function($review) { return substr('4', $review->rate) !== false; }); echo '<pre>';print_r(count($div2)); $div3 = array_filter($reviews, function($review) { return substr('3', $review->rate) !== false; }); echo '<pre>';print_r(count($div3)); $div4 = array_filter($reviews, function($review) { return substr('2', $review->rate) !== false; }); echo '<pre>';print_r(count($div4)); $div5 = array_filter($reviews, function($review) { return substr('1', $review->rate) !== false; });
but error of can count string , integer value.
i think give better performance. declare variables $count1
, $count2
... before loop. keep increment respective variable based on rating value. using $value->rate
objects inside array.
foreach ($myarray $key => $value) { switch ($value->rate) { case '1': $count1++; break; case '2': $count2++; break; case '3': $count3++; break; case '4': $count4++; break; case '5': $count5++; break; default: break; } }
why better performance
when use array_filter
, loops on array. so, when use many array_filter
, looping multiple times. but, approach can accomplish 1 loop on array.
Comments
Post a Comment