How to sum two dimensional array values โ€‹โ€‹separately in PHP

Description of the problem : Sum the values โ€‹โ€‹of a two-dimensional array and store 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();

      

Extract working hours as needed:

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: The amount of time worked for a specific task.

Example :

Objective-1: 7

Problem-2: 11

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

+3


source to share


4 answers


This can be done much easier:

$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

Target-1: 7
Target-2: 11

+3


source


Here's my 2 cents (I love PHP 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);
}

      

+2


source


Try it...

$jsonObj = json_decode(
    file_get_contents('test.json'),
    TRUE
);    

$count = array();

foreach($jsonObj['tasks'] as $task) {
    $count[i] = 0;
    $count[i] += $count[i] + (int)$task['work_hours']['Monday'];
    $count[i] += $count[i] + (int)$task['work_hours']['Tuesday'];
    $count[i] += $count[i] + (int)$task['work_hours']['Wednesday'];
    $count[i] += $count[i] + (int)$task['work_hours']['Thursday'];
    $count[i] += $count[i] + (int)$task['work_hours']['Friday'];
    $count[i] += $count[i] + (int)$task['work_hours']['Saturday'];
    $count[i] += $count[i] + (int)$task['work_hours']['Sunday'];  
}

echo "Task 1 = " . $count['0'] . "\n" ."Task 2 = " . $count['1'];

      

+1


source


This was my solution (some notes below):

$data = json_decode(
    file_get_contents('test.json'),
    TRUE
);

//die(print_r($json));

$tasks = Array();

$work_days = Array('Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday');

foreach($data['tasks'] as $task) {

    //set starting hours at 0
    $tasks[$task['task_name']] = 0;

    foreach($task['work_hours'] as $hours) {
        foreach($work_days as $day) {
            if(isset($hours[$day])) {
                $tasks[$task['task_name']] += (int) $hours[$day];
            }
        }
    }

}

print_r($tasks);

      

First you want print_r () decoded json - then look at the source code, you get a great overview of how arrays are composed:

enter image description here

0


source







All Articles