$type_count = 0;
foreach($arr as $v) {
if(array_key_exists('type', $v)) $type_count++;
}
Answer from Amber on Stack OverflowYou can use:
count($array, COUNT_RECURSIVE);
Count number of leaves in nested array tree
Does this work for what you need?
$dates = array(array(array("2011-11-18 00:00:00" => C), array("2011-11-18 00:00:00" => I),array
("2011-11-18 00:00:00" => S)),
array(array("2011-11-22 00:00:00" => C), array("2011-11-22 00:00:00" => S)));
$date_count = array(); // create an empty array
foreach($dates as $date) { // go thought the first level
foreach($date as $d) { // go through the second level
$key = array_keys($d); // get our date
// here we increment the value at this date
// php will see it as 0 if it has not yet been initialized
$date_count[$key[0]]++;
}
}
// show what we have
print_r($date_count);
Prints:
Array ( [2011-11-18 00:00:00] => 3 [2011-11-22 00:00:00] => 2 )
Note: this assumes that you will always be getting data as you structured your array and that each date will be formatted the same. If you can't assume each date will be formatted, this would be a simple conversion using the date() function. If you can't assume that you will get data structured exactly like this, the best way to tackle that would probably be through a recursive function.
This can be done with a simple iteration:
$counts = array();
foreach ($array as
subarr) {
// Add to the current group count if it exists
if (isset($counts[$subarr['group']]) {
$counts[$subarr['group']]++;
}
// or initialize to 1 if it doesn't exist
else $counts[$subarr['group']] = 1;
// Or the ternary one-liner version
// instead of the preceding if/else block
$counts[$subarr['group']] = isset($counts[$subarr['group']]) ? $counts[$subarr['group']]++ : 1;
}
###Update for PHP 5.5
In PHP 5.5, which has added the array_column() function to aggregate an inner key from a 2D array, this can be simplified to:
$counts = array_count_values(array_flip(array_column($array, 'group')));
This can be done with a simple array_map function
$array = array_map(function($element){
return $element['group'];
}, $array1);
$array2 = (array_count_values($array));
print_r($array2);
A bit late but this is a clean way to write it.
$totalTickets = array_sum(array_map("count", $tickets));
Assuming $tickets is your multi-dimensional array.
I've expanded the code to give an explained example because array_map might be new to some
$tickets = array(
"type1" => array(
"ticket1" => array(),
"ticket2" => array(),
"ticket3" => array(),
),
"type2" => array(
"ticket4" => array(),
"ticket5" => array(),
"ticket6" => array(),
"ticket7" => array(),
),
"type3" => array(
"ticket8" => array()
)
);
// First we map count over every first level item in the array
// giving us the total number of tickets for each type.
$typeTotals = array_map("count", $tickets);
// print_r($typeTotals);
// $type_totals --> Array (
// [type1] => 3,
// [type2] => 4,
// [type3] => 1
// )
//Then we sum the values of each of these
$totalTickets = array_sum($typeTotals);
print($totalTickets);
// $totalTickets --> 8
So because we don't care about the intermediate result of each type we can feed the result into array_sum
$totalTickets = array_sum(array_map("count", $tickets));
$count = 0;
foreach ($array as $type) {
$count+= count($type);
}
Create a results array. Then iterate the outer array, and inside the loop iterate the child array and increment the results array accordingly:
$data = array(
"barack obama" => array(0,50,150,250,600,900,45,150,1050),
"tom jones" => array(80,120,150,75,250,80,1100,1900),
"bob mugabe" => array(50,120,10,0,250,900,600,45,1000,1010),
);
$results = array(); // create an empty array to store our results
foreach ( $data as $item ): // loop the outer array
foreach ( $item as $key => $value ): // loop the inner array
if ( array_key_exists($value,$results) ){ // check if value is already in results, if not set to 1, otherwise increment
$results[$value] = $results[$value] + 1;
} else {
$results[$value] = 1;
}
endforeach;
endforeach;
// show our results array
print "<pre>";
print_r($results);
Iterate over the multi-dimensional array like this:
<?php
$data = array(
'barack_obama' => array('19', '92', '27', '55', '57', '1409', '1384', '1362', '1345', '1280'),
'united_states' => array('72', '81', '89', '90', '92', '21', '23', '27', '32', '47', '55'),
);
$aggregator = [];
foreach (array_keys($data) as $i) {
for ($j = 0, $entryCount = count($data[$i]); $j < $entryCount; $j++) {
$index = $data[$i][$j];
$aggregator[$index] = isset($aggregator[$index]) ? $aggregator[$index] + 1 : 1;
}
}
var_export($aggregator);
The result:
array ( 19 => 1, 92 => 2, 27 => 2, 55 => 2, 57 => 1, 1409 => 1, 1384 => 1, 1362 => 1, 1345 => 1, 1280 => 1, 72 => 1, 81 => 1, 89 => 1, 90 => 1, 21 => 1, 23 => 1, 32 => 1, 47 => 1, )
To count the keys in a two dimensional array with a search I would do this -
function countKeys($array,$search){
$key_count = array(); // new array
foreach($array as $record) {
$keys = array_keys($record);
foreach($keys as $key){
if($key == $search){ // check against the search term
array_push($key_count, $key); // add the key to the new array
}
}
}
return count($key_count); // just count the new array
}
echo countKeys($records, 'last_name');
EXAMPLE
array_keys()
count()
For a 2 dimensional array try:
$result = count(array_column($array, $key));
PHP >= 5.5.0 needed for array_column() or use the PHP Implementation of array_column()
Use $sum as array and get correct value of multiarray:
$sum = array(
'clicks' => 0,
'views' => 0
);
foreach ($data as $id => $value) {
$sum['clicks'] += $value['clicks'];
$sum['views'] += $value['views'];
}
dd($sum);
foreach ($data as $k => $subArray) {
$valueSum[] = $subArray['views'];
$clickSum[] = $subArray['clicks'];
}
echo array_sum($valueSum);
echo array_sum($clickSum);
this is also a clean and easy way .
Just one line more:
$args = array_column($arr, 'Fulfill');
$sum = array_sum($args)/count($args);
Put the result of array_column() in a variable. Then you can get the length of that array.
$fulfills = array_column($arr, 'Fulfill');
$avg = array_sum($fulfills) / count($fulfills);
You can simply use array_count_values along with call_user_func_array like as
array_count_values(call_user_func_array('array_merge', $array));
In PHP >= 5.6 you can use the argument unpacking instead of calling the call_user_func_array():
$result = array_count_values(array_merge(...$array));
Read more: Argument unpacking via ...