問題陳述:總結二維數組的值並將其單獨保存。如何在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]";
....
預期結果:工作時間particu的總和較低的任務。
例:
任務-1:7
任務-2:11
不幸的是我的邏輯去錯地方。 幫助,將不勝感激。
非常感謝,它w非常好。 – WEshruth