I wanna know how to iterate an array to count elements in PHP, I’ve trying next,
foreach ($items as $item) {
$tm[$item->provider->name] = [];
foreach ($items as $item) {
$tm[$item->provider->name][$item->product->brand->name] = isset($tm[$item->provider->name][$item->product->brand->name]) ? $tm[$item->provider->name][$item->product->brand->name] + 1 : $tm[$item->provider->name][$item->product->brand->name] = 1;
}
}
But I get a wrong result, I get an array but I get a very high number count as if iterated many timesmany times
The structure of the array is as follows
[{
"id": 1,
"product": {
"id": 1,
"brand": {
"id": 1,
"name": "iphone"
}
},
"provider": {
"id": 1,
"name": "at&t"
}
},
{
"id": 2,
"product": {
"id": 2,
"brand": {
"id": 2,
"name": "iphone"
}
},
"provider": {
"id": 1,
"name": "at&t"
}
},
{
"id": 3,
"product": {
"id": 3,
"brand": {
"id": 3,
"name": "iphone"
}
},
"provider": {
"id": 1,
"name": "t-mobile"
}
}]
2
Answers
From your code example you apparently want to count how many occurrences are for each "thing" in your array, otherwise
count()
would have probably sufficed…Though you are doing a lot of work to pre-init the counting array – that is completely unneeded: read about auto-vivifcation.
Code like so would probably suffice (I’m not following your example code here – you’d need to work out to your needs):
IIUC, you are trying to count the
product->brand->name
values for eachprovider->name
. You can do that using this code:Output (for your sample data):
Demo on 3v4l.org