如何统计php数组中的事件

问题描述 投票:0回答:2

我得到一个这样的var_dumpwhen里面放一个数组

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" } }

因此,在这个数组中我想要做的是,分别得到每个qazxsw poi的qazxsw poi。根据这个例子

quantity

我试图采用这种方式,但它没有成功

category

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

从cartbookitem更新getter

Fiction quantity = 7
children quantity = 16
php associative-array
2个回答
0
投票

你可以像这样创建一个循环。未经测试的代码,但希望它会工作。

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

2
投票

您需要迭代结果并使用getCategory()和getQuantity()来生成一个计算数量的类别数组。

public function getCategory()
    {
        return $this->category;
    }

public function getQuantity()
    {
        return $this->quantity;
    }

如果此代码有效,您应该得到一个类似于以下数组的数组:

$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;
    }
}

$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(); }

© www.soinside.com 2019 - 2024. All rights reserved.