繁体   English   中英

如何在PHP中分别总结二维数组的值

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

问题陈述 :总结二维数组的值并单独保存。

JSON字符串

{
    "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"
        }]
    }]
}

.....
$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();

根据需要提取工作时间:

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]";


....

预期结果:特定任务的工作时数总和。

示例

任务-1:7

任务-2:11

不幸的是我的逻辑出错了。 帮助将不胜感激。

这可以做得更简单:

$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/>';
}

输出

任务-1:7
任务-2:11

这是我的2美分(我喜欢 PHP的数组函数!):

$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);
}

试试这个 ...

$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'];

这是我的解决方案(下面的一些注释):

$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);

首先,你想要print_r()解码的json - 然后查看源代码,你将得到一个很好的视图,如何组成数组:

在此输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM