问题说明:将二维数组的值相加,分别保存。
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
关于php - 如何在PHP中分别求和二维数组的值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31166941/