Count() into a multidimensional array in PHP - php

If I have this array:
Array (
[0] => Array (
[booking_id] => 1
[booking_status] => confirmed
[client_name] => Bale
[client_firstname] => Gareth
[days] => Array (
[day_id] => 2016-11-23,2016-11-24
[room_id] => 2
)
)
)
How can I get the number of item into day_id please?

You can use array_reduce to iterate through array items and get a final result. Take a look at this:
function reduce_func($carry, $item){
if (isset($item['days']) && !empty($item['days']['day_id'])){
$carry += count(array_unique(array_filter(explode(',', $item['days']['day_id']))));
}
return $carry;
}
$result = array_reduce($arr, "reduce_func", 0);
Update
note that you can also provide a callback to the array_filter to filter out your desired entries to be counted, eg. regex checking each entry to be a valid date. Here's PHP manual for array_filter.

$sum = 0;
foreach ($data as $booking) {
$sum += sizeof(explode(",",$booking["days"]["day_id"]));
}

$sum =0;
for ($count = 0; $count < count($data); $count++) {
$booking = $data[$count];
$day_ids = explode(",", $booking['days']['day_id'];
$sum = $sum + count($day_ids);
}

Related

Sum up the array values

Array
(
[0] => Array( [0] => Array( [value] => 25 ) )
[1] => Array( [0] => Array( [value] => 75 ) )
[2] => Array( [0] => Array( [value] => 10 ) )
[3] => Array( [0] => Array( [value] => 10 ) )
)
I am working on a custom module in drupal and need to sum up the [value],
However I tried different approaches using array_column, array_sum, but didn't get the solution.
Any help would be appreciated. Thanks.
Code
$contributionDetails = $node->get('field_contributions')->getValue();
foreach ( $contributionDetails as $element ) {
$p = Paragraph::load( $element['target_id'] );
$text[] = $p->field_contribution_percentage->getValue();
}
You could make use of array_map here instead of an accumulator:
$arraySum = array_map(function ($v) {
return reset($v)['value'];
}, $text);
print_r(array_sum($arraySum)); // 120
Edit, as a full example:
$values = [
[['value' => 25]],
[['value' => 75]],
[['value' => 10]],
[['value' => 10]],
];
echo array_sum(array_map(function ($v) {
return reset($v)['value'];
}, $values)); // 120
A couple of loops and an accumulator is one way to achieve this
$tot = 0;
foreach ($array as $a){
foreach ($a as $b){
$tot += $b['value'];
}
}
echo $tot;
Or if you are sure there will always only be one occurance of the inner array.
$tot = 0;
foreach ($array as $a){
$tot += $a[0]['value'];
}
echo $tot;
Or using the code you just posted
$contributionDetails = $node->get('field_contributions')->getValue();
$tot = 0;
foreach ( $contributionDetails as $element ) {
$p = Paragraph::load( $element['target_id'] );
$text[] = $p->field_contribution_percentage->getValue();
$tot += $p->field_contribution_percentage->getValue();
}
echo $tot;
So you have an array containing 2 arrays which have the index 'value', you just need to loop each array using nested foreach and a variable $sum which sum up the value on each iteration.
Try this code:
<?php
$sum = 0;
foreach($array as $value) {
foreach ($value as $v){
$sum += $v['value'];
}
}
echo $sum;
This will output 120

How to get the factorial value of each number in an array?

I am trying to get an factorial value of each item in array by using this method but this outputs only one value
can any body help me finding where i am doing wrong?
function mathh($arr, $fn){
for($i = 1; $i < sizeof($arr); $i++){
$arr2 = [];
$arr2[$i] = $fn($arr[$i]);
}
return $arr2;
}
$userDefined = function($value){
$x = 1;
return $x = $value * $x;
};
$arr = [1,2,3,4,5];
$newArray = mathh($arr, $userDefined);
print_r($newArray);
You're going to need a little recursion so in order to do that you need to pass the lambda function into itself by reference:
function mathh($arr, $fn){
$arr2 = []; // moved the array formation out of the for loop so it doesn't get overwritten
for($i = 0; $i < sizeof($arr); $i++){ // starting $i at 0
$arr2[$i] = $fn($arr[$i]);
}
return $arr2;
}
$userDefined = function($value) use (&$userDefined){ // note the reference to the lambda function $userDefined
if(1 == $value) {
return 1;
} else {
return $value * $userDefined($value - 1); // here is the recursion which performs the factorial math
}
};
$arr = [1,2,3,4,5];
$newArray = mathh($arr, $userDefined);
print_r($newArray);
The output:
Array
(
[0] => 1
[1] => 2
[2] => 6
[3] => 24
[4] => 120
)
I wanted to expand on this some since you're essentially (in this case) creating an array map. This could be handy if you're doing additional calculations in your function mathh() but if all you want to do is use the lambda function to create a new array with a range you could do this (utilizing the same lambda we've already created):
$mapped_to_lambda = array_map($userDefined, range(1, 5));
print_r($mapped_to_lambda);
You will get the same output, because the range (1,5) of the mapped array is the same as your original array:
Array
(
[0] => 1
[1] => 2
[2] => 6
[3] => 24
[4] => 120
)

PHP Function for Comparing Elements in Different Arrays

I have two arrays like so (however there can be more or less than 2 (any amount)):
[0] => Array
(
[assessedUsers] => Array
(
[0] => Array
(
[scores] => Array
(
[0] => 10
[1] => 10
[2] => 10
[3] => 10
)
)
[1] => Array
(
[scores] => Array
(
[0] => 9
[1] => 10
[2] => 0
[3] => 9
)
)
)
)
Where the length of the scores array is always the same in both arrays.
I would like to take each element from each array, one by one, and average them, then append them into a new array.
For example, the output of my desired function would look like this:
[1] => Array
(
[scores] => Array
(
[0] => 9.5
[1] => 10
[2] => 5
[3] => 9.5
)
)
Is there a function that can do this, or do I need a couple nested for() loops? If I need to use forl loops how would I go about doing it? I'm a little confused on the logic behind it.
Currently what I have is:
for ($i = 0; $i < sizeof($data["assessedUsers"]); $i++) {
for ($j = 0; $j < sizeof($data["assessedUsers"][$i]["scores"]); $j++) {
}
}
and I'm a little confused as to what to where to go next. Thanks in advance!
$mean = array_map( function($a, $b) { return ($a + $b) / 2; },
$data['assessedUsers'][0]['scores'],
$data['assessedUsers'][1]['scores']
);
var_dump($mean);
And append $mean anywhere you want. Or do you have more than 2 arrays? You did not state it in your question.
ps: for any number of subarrays
$arr = array(
array('scores' => array(10,10,10,10)),
array('scores' => array(9,10,0,9)),
array('scores' => array(1,2,3,4))
);
// remove arrays from the key
$tmp = call_user_func_array( function() { return func_get_args(); },
array_map( function($a) { return $a['scores']; }, $arr)
);
// add arrays by each element
$mean = array_map( function($val, $ind) use($tmp) {
$sum = 0;
foreach($tmp as $i => $t)
$sum += $t[$ind];
return $sum / ($i + 1);
}, $tmp[0], array_keys($tmp[0]));
var_dump($mean);
Probably two loops:
$newarray();
foreach($main_array as $user) {
foreach($user['assessedUser'][0]['scores'] as $score_key => $user0_value) {
$user1_value = $user['assessedUser'][1]['scores'][$score_key];
$average = ($user1_value + $user0_value) / 2;
... stuff into new array
}
}
I have solution for you, hope this help :)
$scores = array();
for ($i = 0; $i < sizeof($data["assessedUsers"]); $i++) {
for ($j = 0; $j < sizeof($data["assessedUsers"][$i]["scores"]); $j++) {
if(isset($scores[$j])){
$scores[$j] = ($scores[$j] + $data["assessedUsers"][$i]["scores"][$j]) / ($i +1);
}else{
$scores[] = $data["assessedUsers"][$i]["scores"][$j];
}
}
}
$scores[] = $scores;
view Example :)
http://codepad.org/upPjMEym

Comparing 2 arrays and adding similar values

I have 2 arrays in PHP. One of them holds a list of dates, the other a list of numbers.
Array1
(
[0] => 2010-06-14
[1] => 2010-06-14
[2] => 2010-06-14
[3] => 2014-01-26
[4] => 2014-01-26
)
Array2
(
[0] => 120
[1] => 100
[2] => 60
[3] => 140
[4] => 30
)
The value [0] in Array2 belongs with the date [0] in Array1. What I am trying to do is add all of the values in Array2 together, based on the date. Any dates that match should have their values added together. So for example at the end I would like something like:
$date = 2010-06-14;
$value = 280;
$date = 2014-01-26;
$value = 170;
...and so on.
I've searched though the site but was unable to find exactly what I needed. Any help would be appreciated...
You can iterate $values, and get the corresponding date from $dates to use as the key in your result array.
foreach ($values as $key => $value) {
$result[$dates[$key]] = $value + ($result[$dates[$key]] ?? 0);
}
The output will be like this:
array (size=2)
'2010-06-14' => int 280
'2014-01-26' => int 170
$sum=0; // New Element
$Array3[][]=0; // New 2D array
$p=0; // Counter for 2D array
for($i=0;$i<5;$i++) // Single loop for traversing
{
$date=Array1[$i]; // Start for a date
while($date==Array1[$i]){ // For for Similar date
$sum=$sum+Array2[$i]; // Adding values of similar date
$i++; // Increment array
}
$Array3[$p]["date"]=$date; // Array3 date element
$Array3[$p]["sum"]=$sum; // Array4 date element
$i--; // Reducing a value which is incremented in while loop
}
Array3 is like
Array3
(
[0] => array( 'date' => " ",'sum' => " ")
[1] => array( 'date' => " ",'sum' => " ")
)
Are you trying to count all of the values in Array2 that have an entry in Array1 that matches some predefined target value?
If so, this for loop version should work:
private function forLoopVersion($array1, $array2, $target) {
$result = 0;
for ($i = 0; $i < count($array1); ++$i) {
if ($array1[$i] == $target) {
$result += $array2[$i];
}
}
return $result;
}
Also, this foreach loop version might work, but I do not know if the $key for $array1 can be used to index an element in $array2. You could try it:
private function foreachLoopVersion($array1, $array2, $target) {
$result = 0;
foreach ($array1 as $key => $value) {
if ($value == $target) {
$result += $array2[$key];
}
}
return $result;
}
$newArray = array();
for($i = 0; $i < count(Array1); $i++) {
$newArray[$Array1[$i]] = $Array2[$i];
}
echo $newArray[$date1] + $newArray[$date2];
Put the dates as keys to for easy math.

php array conversion help needed

$cnt[0]=>Array( [0] => 0 [1] => 0 [2] => 0 ),
$cnt[1] => Array ( [0] => 1 [1] => 0 [2] => 0 )
i want convert this array to below result,
$cnt[0]=(0,0);
$cnt[1]=(0,0);
$cnt[2]=(0,1);
any php function there to convert like this format,
Thanks,
Nithish.
function flip($arr)
{
$out = array();
foreach ($arr as $key => $subarr)
{
foreach ($subarr as $subkey => $subvalue)
{
$out[$subkey][$key] = $subvalue;
}
}
return $out;
}
see more example in
PHP - how to flip the rows and columns of a 2D array
I'm interpreting your expected output to be something like a list of pairs:
$pairs = array(
array(1,0),
array(0,0),
array(0,0)
);
You'd simply check that the sub-arrays are the same length, and then use a for loop:
assert('count($cnt[0]) == count($cnt[1])');
$pairs = array();
for ($i = 0; $i < count($cnt[0]); ++$i)
$pairs[] = array($cnt[0][$i], $cnt[1][$i]);

Categories