如何计算php数组中的出现次数

时间:2018-07-31 11:24:26

标签: php associative-array

在其中放置一个数组时,我得到了一种var_dump

array(3) 
[0]=> object(AppBundle\Entity\CartBookItem)#196 (5)             
{["bookID":protected]=> int(1) 
["quantity":protected]=> string(2) "10" 
["name":protected]=> string(12) "Harry Potter" 
["price":protected]=> int(700) 
["category":protected]=> string(8) "Children" } 

[1]=> object(AppBundle\Entity\CartBookItem)#184 (5) 
{["bookID":protected]=> int(3) 
["quantity":protected]=> string(1) "6" 
["name":protected]=> string(14) "Harry Potter 2" 
["price":protected]=> int(700) 
["category":protected]=> string(8) "Children" } 

[2]=> object(AppBundle\Entity\CartBookItem)#195 (5) 
{ ["bookID":protected]=> int(2) 
["quantity":protected]=> string(1) "1" 
["name":protected]=> string(9) "the Beast" 
["price":protected]=> int(544) 
["category":protected]=> string(8) "Fiction" } }

[3]=> object(AppBundle\Entity\CartBookItem)#195 (5) 
{ ["bookID":protected]=> int(2) 
["quantity":protected]=> string(1) "7" 
["name":protected]=> string(9) "the Beast 2" 
["price":protected]=> int(544) 
["category":protected]=> string(8) "Fiction" } }

因此,在此数组中,Im试图做的是,分别获取每个quantity的{​​{1}}。根据这个例子

category

我尝试过这种方法,但效果不佳

Fiction quantity = 7
children quantity = 16

有人可以帮助我如何分别获取数量计数吗?

更新 来自cartbookitem的吸气剂

foreach ($bookItems as $key => $bookItem) {
   $q_counts = array_count_values(
      array_column($bookItem, 'category')
   );
}

2 个答案:

答案 0 :(得分:2)

您需要遍历结果,并使用getCategory()和getQuantity()来生成一系列计算数量的类别。

$quantities = [];

foreach ($books as $book) {
    // We need to do an isset check because += on an undefined element
    // will throw an exception.
    //
    // You can remove this with an inventive ?? ternary see
    // https://wiki.php.net/rfc/isset_ternary for example uses.
    if (!isset($quantities[$book->getCategory()])) {
        $quantities[$book->getCategory()] = $book->getQuantity();   
        continue;
    }

    $quantities[$book->getCategory()] += $book->getQuantity();
}

如果此代码有效,则应以类似于以下内容的数组结尾:

['Children' => 16, 'Fiction' => 8]

3v4l example

答案 1 :(得分:0)

您可以创建这样的循环。未经测试的代码,但希望它能工作。

$data=array();
foreach($bookItems as $key => $bookItem){
    if(isset($data[$bookItem->category]) && !empty($data[$bookItem->category])){
        $data[$bookItem->category]=$data[$bookItem->category]+$bookItem->quantity;
    }else{
        $data[$bookItem->category]=$bookItem->quantity;
    }
}