Using the variable $arr for your array, you could do this:
$out = array();
foreach (
key => $value){
foreach ($value as $key2 => $value2){
$index = $key2.'-'.$value2;
if (array_key_exists($index, $out)){
$out[$index]++;
} else {
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 (
key => $value){
foreach ($value as $key2 => $value2){
if (array_key_exists($key2, $out) && array_key_exists($value2,
key2])){
key2][$value2]++;
} else {
key2][$value2] = 1;
}
}
}
Output:
Array
(
[07/11] => Array
(
[134] => 2
[145] => 2
)
[07/12] => Array
(
[134] => 1
[99] => 1
)
)
Answer from Expedito on Stack OverflowUsing the variable $arr for your array, you could do this:
$out = array();
foreach (
key => $value){
foreach ($value as $key2 => $value2){
$index = $key2.'-'.$value2;
if (array_key_exists($index, $out)){
$out[$index]++;
} else {
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 (
key => $value){
foreach ($value as $key2 => $value2){
if (array_key_exists($key2, $out) && array_key_exists($value2,
key2])){
key2][$value2]++;
} else {
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);
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);
}
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);
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 ($arr as $ar) {
$a[] = $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) ));
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.
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.
if your array is always going to have only two dimensions, you might use this:
$finalArray = array();
foreach ($fffarray as $array)
{foreach ($array as $key => $string)
{$finalArray[$string] = $finalArray[$string] + 1;}}
this will count how many occurences of each value in all subarrays
Try building a new array that keeps count like this:
$newArray = array(
array("Software Engineer"),
array("Hampelmann", "Software Engineer")
);
$countArray = array();
foreach($newArray as $tempArray){
foreach($tempArray as $key => $value){
if(array_key_exists($value, $countArray)){
$countArray[$value] = $countArray[$value] + 1;
} else {
$countArray[$value] = 1;
}
}
}
echo '<pre>'.print_r($countArray, true).'</pre>';
The output comes out like:
Array
(
[Software Engineer] => 2
[Hampelmann] => 1
)
As you asked in comment,Please try this:-
<?php
$array = array( '1'=> array('0'=>"Extension", '1'=> 1, '2'=>"3,00 " ), '2'=> array('0'=>"Physics",'1'=>"1","3,00 " ),'3'=> array('0'=>"Physics",'1'=>1,"6,00 "),'4'=> array('0'=>"Desk",'1'=>4,"127,00 "),'5'=> array('0'=>"assistance",'1'=>1,"12,50 " ),'6'=> array('0'=>"Extension",'1'=>1,"3,00 "));
$count = array();
$i = 0;
foreach ($array as $key=>$arr) {
// Add to the current group count if it exists
if (isset($count[$i][$arr[0]])) {
$count[$i][$arr[0]]++;
}
else $count[$i][$arr[0]] = 1;
$i++;
}
print_r($count);
?>
Output:- https://eval.in/379176
Looping is the answer.
<?php
// untested
$counts = Array();
foreach( $array as $subArray ){
$value = $subArray[0];
$counts[ $value ] = ( isset($counts[ $value ]) )
? $counts[ $value ] + 1
: 1;
}
var_dump( $counts);
this should work with unlimited depth starting from a main array like
$array = array(
'children' => array( /* ADD HERE INFINITE COMBINATION OF CHILDREN ARRAY */ ),
'id' => #,
'name' => '',
'email' => '',
'points' => #
);
function recursive_children_points($arr) {
global $hold_points;
if (isset($arr['points'])) {
$hold_points[] = $arr['points'];
}
if (isset($arr['children'])) {
foreach ($arr['children'] as $children => $child) {
recursive_children_points($child);
}
}
return $hold_points;
}
$points = recursive_children_points($array);
print "<pre>";
print_r($points);
/**
// OUTPUT
Array
(
[0] => 99999
[1] => 7
[2] => 4
[3] => 3
[4] => 666
[5] => 43
)
**/
print "<pre>";
In my opinion this calls for recursion because you'll do the same thing over each flat level of the array: add the points.
so you'll need to
- loop over each array
- add points found
- if we find any children, do it again but with children array
while keeping track of levels and jumping out if you reach your limit
With that in mind I thought of the following solution:
<?php
$values = array();
//first
$values[] = array('name'=>'andrej','points'=>1,'children'=>array());
$values[] = array('name'=>'peter','points'=>2,'children'=>array());
$values[] = array('name'=>'mark','points'=>3,'children'=>array());
//second
$values[0]['children'][] = array('name'=>'Sarah','points'=>4,'children'=>array());
$values[2]['children'][] = array('name'=>'Mike','points'=>5,'children'=>array());
//third
$values[0]['children'][0]['children'][] = array('name'=>'Ron','points'=>6,'children'=>array());
//fourth
$values[0]['children'][0]['children'][0]['children'][] = array('name'=>'Ronny','points'=>7,'children'=>array());
//fifth
$values[0]['children'][0]['children'][0]['children'][0]['children'][] = array('name'=>'Marina','points'=>10,'children'=>array());
//sixth
$values[0]['children'][0]['children'][0]['children'][0]['children'][0]['children'][] = array('name'=>'Pjotr','points'=>400,'children'=>array());
function collect_elements($base, $maxLevel,$child='children',$gather='points', &$catch = array(), $level = 0) {
/* I pass $catch by reference so that all recursive calls add to the same array
obviously you could use it straight away but I return the created array as well
because I find it to be cleaner in PHP (by reference is rare and can lead to confusion)
$base = array it works on
$maxLevel = how deep the recursion goes
$child = key of the element where you hold your possible childnodes
$gather = key of the element that has to be collected
*/
$level++;
if($level > $maxLevel) return; // we're too deep, bail out
foreach ($base as $key => $elem) {
// collect the element if available
if(isset($elem[$gather])) $catch[] = $elem[$gather];
/*
does this element's container have children?
[$child] needs to be set, [$child] needs to be an array, [$child] needs to have elements itself
*/
if (isset($elem[$child]) && is_array($elem[$child]) && count($elem[$child])){
// if we can find another array 1 level down, recurse that as well
collect_elements($elem[$child],$maxLevel,$child,$gather, $catch,$level);
}
}
return $catch;
}
print array_sum(collect_elements($values,5)) . PHP_EOL;
collect_elements will collect the element you're interested in (until maximum depth is reached) and append it to a flat array, so that you can act on it upon return. In this case we do an array_sum to get the total of poins collected
Only the first for parameters are interesting:
collect_elements($base, $maxLevel,$child='children',$gather='points'
not optional:
$base is the array to work on
$maxLevel is the maximum depth the function needs to descend into the arrays
optional:
$child defines the key of the element that contains the children of current element (array)
$gather defines the key of the element that contains what we want to gather
The remaining parameters are just ones used for recursion