I have an Array like below, is there any way to count the total number of occurrences of CID.
For example:
CID = 992010000021102
I want to count the result as 2
– Laravel 6, php 7.4
{
"status": true,
"message": null,
"data": [
[
{
"cid": "99201000021102",
"mailaddress": "[email protected]"
},
{
"cid": "99201000021105",
"mailaddress": "[email protected]"
}
],
[
{
"cid": "00003900062153",
"mailaddress": "[email protected]"
}
],
[
{
"cid": "99201000021102",
"mailaddress": "[email protected]"
}
],
[
{
"cid": "99201000021101",
"mailaddress": "[email protected]"
}
]
]
}
I tried running the loops but the result is not as expected.
5
Answers
To count the total number of occurrences of a specific value in an array, you can use a loop to iterate through the array and increment a counter variable each time the value is found. For example in your case..
You can try this:
It will print:
Because in each array in the main array we have some objects, we need the nested loop. Each time we check if that
CID
exist in the final array if yes, we sum the occurrence with 1 otherwise we will push newCID
with the occurrence of 1.You can get your result in jQuery also,
Try this.
You can use collection helpers of Laravel on your data array, pretty simple
Convert you data array to collection and flatten 1 level and groupBy "cid" column
$collectionResult = collect($data)->flatten(1)->groupBy(‘cid’);
$data variable is data array get from your response, and flatten need to be done as per your data set from your data we need to apply only one level flatten to get data as stream to group By properly.
Print output result, you will get your expected results.
A simple solution using array_filter:
Explanation:
$v[0]->cid
is compared against the value we search for the valuefunction
that’s passed as the second parameter toarray_filter
which will determine which items would end up in the result, while$yourarray->data
is passed as the first parameterarray_filter
is an array that contains the items for which thefunction
wastrue
and nothing elsecount
we get the number of elements in the filtered arrayAdditionally, if you do not know the value to search for in advance, use the
use
specification, like