I have one problem with PHP array. I have the following array:
$arr = array(
1 => array(1, 2),
2 => array(1,2,3),
3 => array(4,array(4,4,4))
);
I want to know how many element in total.
Ex:
echo count($arr); // result: 3
but I want: 7
I want to do this without loop.
Do any one know, please help?
Take one of this
$arr = array(
1 => array(1, 2),
2 => array(1, 2, 3),
3 => array(4, array(4, 4, 4))
);
// iterate over values to find out their size/
var_dump(array_reduce($arr, function($count, $inner_array)
{ return $count + sizeof($inner_array); }, 0));
// merge all value to one big array
var_dump(count(call_user_func_array('array_merge', $arr)));
// create new array with counts of items
var_dump(array_sum(array_map('sizeof', $arr)));
<?php
$arr = array(
1 => array(1, 2),
2 => array(1,2,3),
3 => array(4,array(4,4,4))
);
$sum = 0;
foreach($arr as $a => $b) {
$sum += count($b);
}
echo $sum;
?>
$arr = array(
1 => array(1, 2),
2 => array(1,2,3),
3 => array(4,array(4,4,4))
);
$count = 0;
foreach ($arr as $level) {
$count+= count($level);
}
echo $count;
If your array as follows you can use another method for get 7
$arr = array(
1 => array(1, 2),
2 => array(1,2,3),
3 => array(4,8)
);
echo (count($arr, COUNT_RECURSIVE) - count($arr));
Related
am trying to get output of following array in one format. its not getting
<?php
$distance_covered = array( '1_JAN_2017' => array('DRIVER_1' => array(2, 5, 3),'DRIVER_2' => array(3, 2, 6, 9)),
'2_JAN_2017' => array('DRIVER_1' => array(3, 9), 'DRIVER_3' => array(1, 4, 8)),
'3_JAN_2017' => array('DRIVER_4' => array(9), 'DRIVER_1' => array(2, 7, 5, 2)),
'4_JAN_2017' => array('DRIVER_1' => array(5, 3, 3, 2), 'DRIVER_4' => array(4, 9, 8, 5)),
'5_JAN_2017' => array('DRIVER_2' => array(8, 5), 'DRIVER_5' => array(3, 9, 7)),
'6_JAN_2017' => array('DRIVER_5' => array(2, 1, 7, 5), 'DRIVER_4' => array(1, 9, 6)),
'7_JAN_2017' => array('DRIVER_4' => array(5, 2, 9), 'DRIVER_3' => array(4, 1, 6)), );
The above is my array
i want output in the following format
Output: Array ( [DRIVER_1] => 51, [DRIVER_2] => 33, [DRIVER_3] => 24, [DRIVER_4] => 67, [DRIVER_5] => 34 )
this is the sum of distance travelled by each driver in all trips
i tried code like this,anybody knows please help
$res = array();
foreach($distance_covered as $value) {
foreach($value as $key => $number) {
(!isset($res[$key])) ?
$res[$key] = $number :
$res[$key] += $number;
}
}
print_r($res);
?>
This one works for me
$res = array();
foreach($distance_covered as $value)//the array which you have given us
{
foreach($value as $key => $number) //loop over array of date
{
if(!isset($res[$key]))//check if the key exist in over defined array if no then run this
{
$res[$key] = array_sum($number);// Sum all distances of that driver
continue;//set the key and continue the foreach...
}
$res[$key] += array_sum($number);// Sum all distances of that driver
}
}
print_r($res);
die;
And the Output is
Array
(
[DRIVER_1] => 51
[DRIVER_2] => 33
[DRIVER_3] => 24
[DRIVER_4] => 67
[DRIVER_5] => 34
)
This should work:
$res = array();
foreach($distance_covered as $value) {
foreach($value as $key => $number) {
foreach ($number as $n) {
if (isset($res[$key])) {
$res[$key] += $n;
} else {
$res[$key] = $n;
}
}
}
}
print_r($res);
Just traverse through array of arrays.
$distance_covered = array(
'1_JAN_2017' => array('DRIVER_1' => array(2, 5, 3),'DRIVER_2' => array(3, 2, 6, 9)),
'2_JAN_2017' => array('DRIVER_1' => array(3, 9), 'DRIVER_3' => array(1, 4, 8)),
'3_JAN_2017' => array('DRIVER_4' => array(9), 'DRIVER_1' => array(2, 7, 5, 2)),
'4_JAN_2017' => array('DRIVER_1' => array(5, 3, 3, 2), 'DRIVER_4' => array(4, 9, 8, 5)),
'5_JAN_2017' => array('DRIVER_2' => array(8, 5), 'DRIVER_5' => array(3, 9, 7)),
'6_JAN_2017' => array('DRIVER_5' => array(2, 1, 7, 5), 'DRIVER_4' => array(1, 9, 6)),
'7_JAN_2017' => array('DRIVER_4' => array(5, 2, 9), 'DRIVER_3' => array(4, 1, 6)), );
// Counting.
$merged = [];
foreach ($distance_covered as $day => $stats) {
foreach ($stats as $driver => $distances) {
if (!isset($merged[$driver])) {
$merged[$driver] = 0;
}
$merged[$driver] += array_sum($distances);
}
}
// Display.
echo "<pre>";
print_r($merged);
echo "</pre>";
You are close, but...
$res = array ();
foreach ( $distance_covered as $value ) {
foreach ( $value as $key=> $driver ) {
if ( isset($res[$key]) == false ){
$res[$key]=0;
}
$res[$key] += array_sum($driver);
}
}
print_r($res);
The first foreach simply splits the data down to the days.
The second one returns elements like $key = 'DRIVER_1' and $driver = array(3, 9).
If this is the first time you've encountered this driver, then you need to ensure that the element in $res exists, so set it to 0.
Once you know there is an element there, you can add in the sum of the values ( 3 & 9 in this case ) using the += array_sum($driver) bit. The += is simply adding to rather than having to say a=a+b, you can say a+=b.
[sarcastic voice] I can't believe everybody overlooked this convoluted function-based one-liner...
Code: (Demo)
var_export(array_map('array_sum', array_merge_recursive(...array_values($distance_covered))));
Output:
array (
'DRIVER_1' => 51,
'DRIVER_2' => 33,
'DRIVER_3' => 24,
'DRIVER_4' => 67,
'DRIVER_5' => 34,
)
*this is virtually guaranteed to process slower than any other posted answer.
Remove the first level associative keys (date strings) with array_values()
Unpack the array of arrays with the "splat operator" (...) and feed to array_merge_recursive() to group values
Sum the subarray values by calling array_sum() on each subarray with array_map()
(This is merely an exercise of thinking outside the box.)
Beyond that no one suggested using a null coalescing operator, so I'll post what that can look like:
$driver_totals = [];
foreach ($distance_covered as $daily_log) {
foreach ($daily_log as $driver => $distances) {
$driver_totals[$driver] = ($driver_totals[$driver] ?? 0) + array_sum($distances);
}
}
var_export($driver_totals);
And if you have a special scenario where you only need to know the distance for a single specific driver, you can call upon array_column() like this:
$target_driver = 'DRIVER_4';
$total_distance = 0;
foreach (array_column($distance_covered, $target_driver) as $distances) {
$total_distance += array_sum($distances);
}
echo "{$target_driver} drove for a distance of {$total_distance}";
*Notice that the order of the drivers within each date array is inconsequential because array_column() is smart enough to find the desired distance subarray.
Finally, if you declare a whitelist array of all possible drivers, you can:
control the order of the drivers in the output
avoid the iterated isset() conditions
ensure that drivers without any distance records are included in the output
Code:
$roster = ['DRIVER_6', 'DRIVER_5', 'DRIVER_4', 'DRIVER_3', 'DRIVER_2', 'DRIVER_1'];
$driver_totals = array_fill_keys($roster, 0);
foreach ($distance_covered as $daily_log) {
foreach ($daily_log as $driver => $distances) {
$driver_totals[$driver] += array_sum($distances);
}
}
var_export($driver_totals);
I have multiple arrays, that get generated when a for loop completes. Now I need to get the total of all these arrays together, but in order, for instance:
array1(2, 4, 6, 8, 10)
array2(2, 4, 6, 8, 10)
I need to add the 2's together, the 4's etc etc
Then put them into another array.
Some combination of array_combine and array_sum seems to be the solution but I can't figure it out.
Any help is greatly appreciated.
You could do this without any php function except count,
$limit = count($array1);
for ($i = 0; $i < $limit; $i++) {
$array_res[$i] = $array1[$i] + $array2[$i];
should work. This will combine your two arrays and add them in the same order. But be sure you used sort or ksort on both of your arrays before if you're not sure they are in the same order.
1st stlye
$a1 = array(
"a" => 2
,"b" => 0
,"c" => 5
);
$a2 = array(
"a" => 3
,"b" => 9
,"c" => 7
,"d" => 10
);
$a3 = array_merge($a1, $a2);
print_r($a3);
2nd style
$a3 = $a1;
foreach($a2 as $k=>$v) {
if(array_key_exists($k,$a3))
$a3[$k] + = $v;
else
$a3[$k] = $v;
}
You should use array_map():
$arr1 = array(2, 4, 6, 8, 10);
$arr2 = array(1, 2, 3, 4, 5);
$arr3 = array_map(
function($foo, $bar){
return $foo+$bar;
},
$arr1, $arr2
);
print_r($arr3); // outputs:
Array
(
[0] => 3
[1] => 6
[2] => 9
[3] => 12
[4] => 15
)
You can do something like this
$a = array(2, 4, 6, 8, 10);
$b = array(2, 4, 6, 8, 10);
$c = array_map("test", $a, $b);
function test($a, $b) {
return $a + $b;
}
print_r($c);
As far as I understand your question You want sum of all the similar digits in both the array:
<?php
$array1= array(2, 4, 6, 8, 10);
$array2=array(2, 4, 6, 8, 10);
$array_sum=array();
foreach($array1 as $key1=>$val1)
{
$sum=0;
foreach($array2 as $key2 => $val2)
{
if($val1==$val2)
{
$sum=$sum+$val1;
}
}
$array_sum[]=$sum;
}
print_r($array_sum);
?>
In php, how do I get the total number of posts (16)?
array1("posts" => 2, "reactions" => 0)
array2("posts" => 4, "reactions" => 4)
array3("posts" => 7, "reactions" => 0)
array4("posts" => 3, "reactions" => 1)
You can use this function
array_merge_recursive
And I made an example for you
<?php
$a = array("posts" => 2, "reactions" => 0);
$b = array("posts" => 4, "reactions" => 4);
$c = array("posts" => 7, "reactions" => 0);
$d = array("posts" => 3, "reactions" => 1);
$array = array_merge_recursive($a,$b,$c,$d);
$sum = array_sum($array['posts']);
echo $sum;
?>
If you want to read more about array_merge_recursive
Follow this Link
Don't know how your variables are named, but some sort of:
$total = 0;
foreach ($arrayofstuff as $item) {
$total += $item['posts'];
}
$numposts = $arr1["posts"]+$arr2["posts"]+$arr3["posts"]+$arr4["posts"]
Do you have them in separate arrays or in one single array? If you have them separately then this would suffice:
$array1 = array("posts" => 2, "reactions" => 0);
$array2 = array("posts" => 4, "reactions" => 4);
$array3 = array("posts" => 7, "reactions" => 0);
$array4 = array("posts" => 3, "reactions" => 1);
$sum = $array1['posts'] + $array2['posts'] + $array3['posts'] + $array4['posts'];
echo $sum;
Outputs:
16
What is the easiest way to achieve:
a => 1, b => 0, c=> 3
a => 0, b => 10, c=> 1
Sum
a => 1, b =>10, c=>4
and
Minus
a => -1, b=> 10, c=> -2
I hope my examples make it clear... If you have any questions please leave a comment
Sum:
$array1 = array('a' => 1, 'b' => 0, 'c' => 3);
$array2 = array('a' => 0, 'b' => 10, 'c' => 1);
$result = array();
foreach ($array1 as $key => $value)
$result[$key] = $value + $array2[$key];
You can implement the difference part similarly.
$sum = $minus = 0;
foreach ($arrays as $key=>$val)
{
$sum += $val;
$minus -= ($val*-1);
}
You want to add orsubstarct the values with same key.
Try to write function with array_walk
http://php.net/manual/en/function.array-walk.php
or put in a loop and add or substarct based on key.
What's the best way in PHP to sort an array of arrays based on array length?
e.g.
$parent[0] = array(0, 0, 0);
$parent[2] = array("foo", "bar", "b", "a", "z");
$parent[1] = array(4, 2);
$sorted = sort_by_length($parent)
$sorted[0] = array(4, 2);
$sorted[1] = array(0, 0, 0);
$sorted[2] = array("foo", "bar", "b", "a", "z");
This will work:
function sort_by_length($arrays) {
$lengths = array_map('count', $arrays);
asort($lengths);
$return = array();
foreach(array_keys($lengths) as $k)
$return[$k] = $arrays[$k];
return $return;
}
Note that this function will preserve the numerical keys. If you want to reset the keys, wrap it in a call to array_values().
I'm upvoting Peter's but here's another way, I think:
function cmp($a1, $a2) {
if (count($a1) == count($a2)) {
return 0;
}
return (count($a1) < count($a2)) ? -1 : 1;
}
usort($array, "cmp");
Try the usort function:
function sortByLength( $arr1, $arr2 )
{
$c1 = count($arr1);
$c2 = count($arr2);
return $c1 < $c2 ? -1 : $c1 == $c2 ? 0 : 1;
}
usort($initial_array,'sortByLength');
edited to respect parameters-by-reference; it's the same answer as #david, anyway
sort() compares by size before quality.
Because all of your rows have the same flat structure, sort() will sort ascending by row size, sort ascending by first elements, then the next elements, etc.
Code: (Demo)
$parent[0] = array(0, 0, 0);
$parent[2] = array("foo", "bar", "b", "a", "z");
$parent[1] = array(4, 2);
$parent[5] = array(11, 2);
$parent[3] = array(1, 21);
$parent[4] = array(11, 1);
sort($parent);
var_export($parent);
Output:
array (
0 =>
array (
0 => 1,
1 => 21,
),
1 =>
array (
0 => 4,
1 => 2,
),
2 =>
array (
0 => 11,
1 => 1,
),
3 =>
array (
0 => 11,
1 => 2,
),
4 =>
array (
0 => 0,
1 => 0,
2 => 0,
),
5 =>
array (
0 => 'foo',
1 => 'bar',
2 => 'b',
3 => 'a',
4 => 'z',
),
)
This performs identically to this use of array_multisort() with iterated calls of count: (Demo)
array_multisort(array_map('count', $parent), $parent);
var_export($parent);
Using usort() is different if only sorting on the counts because in modern PHP it will leave tied comparisons in their original position : (Demo)
usort($parent, fn($a, $b) => count($a) <=> count($b));
var_export($parent);