Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sum up values of two dimensional array separately in PHP

Problem statement: Sum up the values of two dimensional array and save it separately.

JSON string:

{
    "user_name": "USER1",
    "selected_date": "07/27/2015",
    "selected_project": "PROJECT1",
    "tasks": [{
        "task_name": " Task-1",
        "work_hours": [{
            "Monday": " 2"
        },
        {
            "Tuesday": " 1"
        },
        {
            "Wednesday": " 4"
        },
        {
            "Thursday": " 0"
        },
        {
            "Friday": " 0"
        },
        {
            "Saturday": " 0"
        },
        {
            "Sunday": " 0"
        }]
    },
    {
        "task_name": " Task-2",
        "work_hours": [{
            "Monday": " 5"
        },
        {
            "Tuesday": " 1"
        },
        {
            "Wednesday": " 5"
        },
        {
            "Thursday": " 0"
        },
        {
            "Friday": " 0"
        },
        {
            "Saturday": " 0"
        },
        {
            "Sunday": " 0"
        }]
    }]
}

Code

.....
$str_json = file_get_contents('php://input');
$response = json_decode($str_json, true); // decoding received JSON to array
decoded = json_decode($response, true);
$task_counter = count($decoded['tasks']);
$hour_counter = count($decoded['tasks'][0]['work_hours']);
$_tasks = array();
$_hours = array();
$_hours[] = array();

Extracting work hours as required:

for ( $var1 = 0; $var1 <= $task_counter; $var1++)
{
  $_hours[$var1][] = $decoded['tasks'][$var1]['work_hours'][0]['Monday'];
  $_hours[$var1][] = $decoded['tasks'][$var1]['work_hours'][1]['Tuesday'];
  $_hours[$var1][] = $decoded['tasks'][$var1]['work_hours'][2]['Wednesday'];
  $_hours[$var1][] = $decoded['tasks'][$var1]['work_hours'][3]['Thursday'];
  $_hours[$var1][] = $decoded['tasks'][$var1]['work_hours'][4]['Friday'];
  $_hours[$var1][] = $decoded['tasks'][$var1]['work_hours'][5]['Saturday'];
  $_hours[$var1][] = $decoded['tasks'][$var1]['work_hours'][6]['Sunday'];
}

for($var = 0; $var <= $task_counter; $var++)
{
    echo "|";
    for ($var1 = 0; $var1 <= 7; $var1++) 
  {
     echo $_hours[$var][$var1];
  }
}

$_totalArray = array();
for ( $i=0 ; $i<=7; $i++)
{
    foreach($_hours as $num => $values) 
    {
      
       $_totalArray[$i] += $values[$i];
  }
 }
echo "<br>Task-1:$_totalArray[0]";
echo "Task-2:$_totalArray[1]";


....

Expected result: Sum of working hours for particular task(s).

Example:

Task-1: 7

Task-2: 11

Unfortunately my logic going wrong somewhere. Help would be appreciated.

like image 616
WEshruth Avatar asked Dec 05 '25 05:12

WEshruth


2 Answers

This can be done much simpler:

$decoded = json_decode($str_json, true); // decoding received JSON to array

foreach ($decoded['tasks'] as $task) {
    $total = 0;
    foreach ($task['work_hours'] as $day) {
        foreach ($day as $key=>$value) {
            $total += $value;
        }
    }
    echo $task['task_name'] .': ' . $total .'<br/>';
}

Outputs

Task-1: 7
Task-2: 11

like image 98
mittmemo Avatar answered Dec 07 '25 21:12

mittmemo


Here's my 2 cents (I love PHP's array functions!):

$response = json_decode($str_json, true);

foreach($response['tasks'] as $task)
{
    $workHours = [];

    // flatten the $task['work_hours'] array
    // this basically puts all the working hours in one array
    array_walk_recursive($task['work_hours'], function ($x) use (&$workHours) { $workHours[] = $x; });

    echo $task['task_name'] . ": " . array_sum($workHours);
}
like image 23
Quasdunk Avatar answered Dec 07 '25 20:12

Quasdunk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!