count works exactly as you would expect, e.g., it counts all the elements in an array (or object). But your assumption about the array containing four elements is wrong:
- "1" is equal to 1, so
1 => "B"will overwrite"1" => "A". - because you defined 1, the next numeric index will be 2, e.g. "C" is
2 => "C" - when you assigned
2 => "D"you overwrote "C".
So your array will only contain 1 => "B" and 2 => "D" and that's why count gives 2. You can verify this is true by doing print_r($a). This will give
Array
(
[1] => B
[2] => D
)
Please go through Arrays again.
Answer from Gordon on Stack Overflowcount works exactly as you would expect, e.g., it counts all the elements in an array (or object). But your assumption about the array containing four elements is wrong:
- "1" is equal to 1, so
1 => "B"will overwrite"1" => "A". - because you defined 1, the next numeric index will be 2, e.g. "C" is
2 => "C" - when you assigned
2 => "D"you overwrote "C".
So your array will only contain 1 => "B" and 2 => "D" and that's why count gives 2. You can verify this is true by doing print_r($a). This will give
Array
(
[1] => B
[2] => D
)
Please go through Arrays again.
You can use this example to understand how count works with recursive arrays
<?php
$food = array('fruits' => array('orange', 'banana', 'apple'),
'veggie' => array('carrot', 'collard', 'pea'));
// recursive count
echo count($food, COUNT_RECURSIVE); // output 8
// normal count
echo count($food); // output 2
?>
Source
Combination of array_count_values & array_column (PHP 5 >= 5.5.0, PHP 7) should work -
$counts = array_count_values(
array_column($employees, 'position')
);
Output
array(3) {
[1]=>
int(1)
[2]=>
int(2)
[3]=>
int(2)
}
Update
$final = array_filter($counts, function($a) {
return $a >= 2;
});
Output
array(2) {
[2]=>
int(2)
[3]=>
int(2)
}
Demo
array_column — Return the values from a single column of array. array_count_values — Counts all the values of an array.
$positions = array_column($employees, 'position');
print_r(array_count_values($positions));
Output
Array
(
[1] => 1
[2] => 2
[3] => 2
)
you can use array_filter function to filter item which IsRatingQuestion=1
$filterdArray = array_filter($rec,function($item){
if($item['IsRatingQuestion']==1){
return $item;
}
});
count($filterdArray)
You can keep a counter, iterate over the array and, when the condition is true, add to the counter.
$count = 0;
foreach($entries as $entry) {
if (isset($entry['isRatingQuestion']) && $entry['isRatingQuestion'] === 1) {
$count ++;
}
}
echo "$count entries match the condition";
Try array_sum(array_column($input, 'amount'));
array_column will return the values of amount key & array_sum calculate the sum of values in the returned array
Try this one :
function sum($carry, $item)// summing on amount column of the inner array $item
{
$carry += $item["amount"];
return $carry;
}
echo "Amount sum : ".array_reduce($a, "sum");// output : 59
Example :
<?php
/**
* Created by PhpStorm.
* User: lenovo
* Date: 4/2/2017
* Time: 11:17 AM
*/
$array = array
(
array("name"=>"Volvo","amount"=>22,"id"=>18),
array("name"=>"BMW","amount"=>15,"id"=>13),
array("name"=>"Saab","amount"=>5,"id"=>2),
array("name"=>"Land Rover","amount"=>17,"id"=>15)
);
function sum($carry, $item)
{
$carry += $item["amount"];
return $carry;
}
echo "Amount sum : " .array_reduce($array, "sum");// output : 59
Good luck.
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.
Update #2. Lots of information, let me know if I lose you.
I made a couple tiny mistakes (needed to pass $current + 1 instead of $current++, and $levels[$current]++ was in the wrong place) in the last code. I tested this update with your example data; it will work for you. Basically, calc() is a recursive function that goes through every level of the array, counting each index that is an array, and adds that count to the master "counting" array ($levels). You can stick this right into your class, as I did below.
It doesn't return anything on purpose. $levels is passed by reference, and the count of each level is updated directly on it. So the first variable you pass to calc() will be turned into an array, like the one you're looking for in your question.
If your class script looks exactly like that, you should be getting errors. After class someName {, you should only be defining functions and variables. Code that actually performs an action, such as using echo or setting $test = new Test();, needs to be placed after the class definition.
With that said, if you want to execute some code every time you initiate this class, you should put this code in the class's constructor.
Below is what I think you want your class to look like. If you want $data to be in the class, declare the variable with var $data and fill it inside the constructor. If you're confused, let me know and I can update my answer again.
// Your class
class Test
{
// Counts the number of arrays in each level of $data
function calc(&$levels, $current, $parent)
{
if (!isset($levels[$current])) {
$levels[$current] = 0;
}
foreach($parent as $child) {
$levels[$current]++;
if (is_array($child)) {
$this->calc($levels, $current + 1, $child);
}
}
}
}
// Let's use the class! Create an instance of it
$test = new Test();
// Fill the data array
$data = array();
$data['food']['soup']['chicken_noodle'] = '';
$data['food']['soup']['tomato'] = '';
$data['food']['soup']['french onion'] = '';
$data['food']['salad']['house'] = '';
$data['food']['salad']['ceasar'] = '';
$data['drink']['soda']['coke'] = '';
$data['drink']['soda']['sprite'] = '';
$data['drink']['soda']['dr pepper'] = '';
$data['drink']['alcoholic']['whiskey']['Jim Beam'] = '';
$data['drink']['alcoholic']['whiskey']['Jameson'] = '';
$data['drink']['alcoholic']['whiskey']['Bushmills'] = '';
$data['drink']['alcoholic']['vodka']['Stolichnaya'] = '';
$data['drink']['alcoholic']['vodka']['Ketel One'] = '';
$data['drink']['alcoholic']['vodka']['Grey Goose'] = '';
$data['drink']['alcoholic']['vodka']['Belvedere'] = '';
$data['drink']['alcoholic']['rum']['Captain Morgan'] = '';
$data['drink']['alcoholic']['rum']['Bacardi'] = '';
// Count the data for arrays on each level
$count = array();
$test->calc($count, 0, $data);
// Print the results
echo '<pre>';
print_r($count);
exit ('</pre>');
If you want to get the sum of all the elements in all the arrays, you can use
count($arr, COUNT_RECURSIVE);
Try it online