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));
Answer from bigkm on Stack OverflowA 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);
}
PHP has no support for a SQL where sort of thing, especially not with an array of arrays. But you can do the counting your own while you iterate over the data:
$count = array();
foreach($fruit as $one)
{
@$count[$one['color']]++;
}
printf("You have %d green fruit(s).\n", $count['green']);
The alternative is to write yourself some little helper function:
/**
* array_column
*
* @param array $array rows - multidimensional
* @param int|string $key column
* @return array;
*/
function array_column($array, $key) {
$column = array();
foreach($array as $origKey => $value) {
if (isset($value[$key])) {
$column[$origKey] = $value[$key];
}
}
return $column;
}
You then can get all colors:
$colors = array_column($fruit, 'color');
And then count values:
$count = array_count_values($colors);
printf("You have %d green fruit(s).\n", $count['green']);
That kind of helper function often is useful for multidimensional arrays. It is also suggested as a new PHP function for PHP 5.5.
$number_of_green_fruit = 0;
for ($row = 0; $row < 3; $row++) {
if($fruit[$row]["color"]=="green") {
$number_of_green_fruit++;
echo $fruit[$row]["name"] . '<br />';
}
}
You'd have to loop it yourself:
$counts = array();
foreach( $array as $value) {
foreach( $value as
v) {
if( !isset( $counts[
counts[$k] = array();
if( !isset( $counts[
v])) $counts[
v] = 0;
$counts[
v] += 1;
}
}
foreach( $counts as
v1)
foreach(
v => $count)
echo "
v => $count matches\n";
This will print:
stack == 1 => 4 matches
stack == 2 => 2 matches
$occur = array();
foreach ($array as $item) {
foreach ($item as $k => $v) {
$occur["$k == $v"]++;
}
}
You can merge all the inner arrays into one with array_merge and then use array_count_values to get the counts.
$counts = array_count_values(array_merge(...$feetypes));
Merge all the subarray into a single array and apply array_count_values function to get the result
function merageAll($arr) {
$flatArray = array();
foreach(
element) {
if (is_array($element)) {
$flatArray = array_merge($flatArray, merageAll($element));
} else {
$flatArray[] = $element;
}
}
return $flatArray;
}
$res = array_count_values(merageAll($feetypes));
Result
Array
(
[30] => 4
[35] => 2
[50] => 2
[34] => 1
)
function merageAll work if there are values and sub arrays in the array.
Working DEMO LINK
What you can do is, you can loop through the array and put the values of [1] into another array, and apply array_count_values on the resultant array.
$a = array();
foreach (
ar) {
ar[1];
}
print_r(array_count_values($a));
This will give you:
vote1: 1A: 5
If the above is what you are looking for? If you want a shorter version, you can also use array_column.
use array_column($array, 1) to get position[1] elements as array; Then use your array_count_values() to count them.
<?php
$array = [[1,2,3],[2,3,4]];
var_dump(array_count_values ( array_column($array,1) ));
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);
$array = array("Kyle","Ben","Sue","Phil","Ben","Mary","Sue","Ben");
$counts = array_count_values($array);
echo $counts['Ben'];
You can do this with array_keys and count.
$array = array("blue", "red", "green", "blue", "blue");
echo count(array_keys($array, "blue"));
Output:
3
You 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.
Using the variable $arr for your array, you could do this:
$out = array();
foreach ($arr as $key => $value){
foreach ($value as $key2 => $value2){
$index = $key2.'-'.$value2;
if (array_key_exists($index, $out)){
$out[$index]++;
} else {
$out[$index] = 1;
}
}
}
var_dump($out);
Output:
Array
(
[07/11-134] => 2
[07/11-145] => 2
[07/12-134] => 1
[07/12-99] => 1
)
Here's another version that produces it as a multidimensional array:
$out = array();
foreach ($arr as $key => $value){
foreach ($value as $key2 => $value2){
if (array_key_exists($key2, $out) && array_key_exists($value2, $out[$key2])){
$out[$key2][$value2]++;
} else {
$out[$key2][$value2] = 1;
}
}
}
Output:
Array
(
[07/11] => Array
(
[134] => 2
[145] => 2
)
[07/12] => Array
(
[134] => 1
[99] => 1
)
)
<?php
$array = array(array('07/11' => '134'), array('07/11' => '134'), array('07/12' => '145'));
$count = array();
foreach ($array as $val) {
foreach ($val as $key => $subval) {
$count[$key]++;
}
}
print_r($count);
foreach($array as $k => $v) {
$result[$k] = array_count_values($v);
arsort($result[$k]);
}
- Loop through the array (exposing the key) to access each inner array
- Count the values of the inner array (value will be key and count will be value)
- Sort by the values (count) preserving the keys
This should fit your needs:
<?php
$a = array(
'svote001' => array("006", "006", "007"),
'svote002' => array("000", "000", "000"),
'svote003' => array("003", "001", "001"),
);
$resultArray = array();
foreach ($a as $arrayName => $arrayData){
$resultArray[$arrayName] = array();
foreach ($arrayData as $value){
if (empty($resultArray[$arrayName][$value])){
$resultArray[$arrayName][$value] = 1;
}else{
$resultArray[$arrayName][$value]++;
}
}
arsort($resultArray[$arrayName]);
}
var_dump($resultArray);
Edit: AbraCadaver solution is much better, use this one. I will let the answer stay here anyway.
Using a couple of useful builtin functions you can do
$in = [
['CHICAGO', '14', 'MUFFIN A LINE', 'MUFA-D', 'Arm Bearings - Check for play, lubricate if needed.'],
['CHICAGO', '14', 'MUFFIN A LINE', 'MUFA-D', 'Linkage - Check for wear and broken links.'],
['MEMPHIS', '05', 'BREADING LINE 1', 'BRD1-IS', 'Gear Box oil level'],
['MEMPHIS', '05', 'BREADING LINE 1', 'BRD1-IS', 'Bearings visual inspection'],
['MEMPHIS', '05', 'BREADING LINE 1', 'BRD1-IS', 'Electrical Plug condition'],
['CHICAGO', '02', 'JBC LINE 2', 'JBC-BAK-B', 'Plate separator shaft']
];
function grab3($occ)
{
return $occ[3];
}
print_r(array_count_values(array_map('grab3', $in)));
And the result is an array where the values are now the key of an array and the value is the count
Array
(
[MUFA-D] => 2
[BRD1-IS] => 3
[JBC-BAK-B] => 1
)
You can just loop over the array and use the indexes value as a key in an associative array to count. Then $result will contain your desired results.
$data = [
['CHICAGO', '14', 'MUFFIN A LINE', 'MUFA-D', 'Arm Bearings - Check for play, lubricate if needed.',],
['CHICAGO', '14', 'MUFFIN A LINE', 'MUFA-D', 'Linkage - Check for wear and broken links.',],
['MEMPHIS', '05', 'BREADING LINE 1', 'BRD1 - IS', 'Gear Box oil level',],
['MEMPHIS', '05', 'BREADING LINE 1', 'BRD1 - IS', 'Bearings visual inspection',],
['MEMPHIS', '05', 'BREADING LINE 1', 'BRD1 - IS', 'Electrical Plug condition',],
['CHICAGO', '02', 'JBC LINE 2', 'JBC - BAK - B', 'Plate separator shaft',],
];
$result = [];
foreach ($data as $item) {
$index = $item[3];
$result[$index] = isset($result[$index]) ? $result[$index] + 1 : 1;
}
print_r($result);
Will print
Array
(
[MUFA-D] => 3
[BRD1 - IS] => 4
[JBC - BAK - B] => 2
)