目标:要解析以下 json 字符串并分别获取提及的值,稍后将这些分隔值插入 mysql 数据库。
我在JsonLint
tasks,4.1.task_name,4.2 work_hours
{
"user_name": "USER",
"selected_date": "2015-06-08",
"selected_project": "Project1",
"tasks": [
{
"task_name": "task-1",
"work_hours": [
{
"Monday": " 3"
},
{
"Tuesday": " 0"
},
{
"Wednesday": " 2.5"
},
{
"Thursday": " 2"
},
{
"Friday": " 0"
},
{
"Saturday": " 0"
},
{
"Sunday": " 0"
}
]
}
]
}
PHP代码是:
$str_json = file_get_contents('php://input'); //($_POST doesn't work here)
$response = json_decode($str_json, true); // decoding received JSON to array
$jsonIterator = new RecursiveIteratorIterator(
new RecursiveArrayIterator(json_decode($response, TRUE)),
RecursiveIteratorIterator::SELF_FIRST);
foreach ($jsonIterator as $key => $val)
{
if(is_array($val))
{
echo "$key:\n";
}
else
{
echo "$key => $val\n";
echo "$value";
}
}
由于我是JSON和PHP的新手,我无法解决这个问题,我们将不胜感激。
答案 0 :(得分:1)
<?
$json = '{
"user_name": "USER",
"selected_date": "2015-06-08",
"selected_project": "Project1",
"tasks": [
{
"task_name": "task-1",
"work_hours": [
{
"Monday": " 3"
},
{
"Tuesday": " 0"
},
{
"Wednesday": " 2.5"
},
{
"Thursday": " 2"
},
{
"Friday": " 0"
},
{
"Saturday": " 0"
},
{
"Sunday": " 0"
}
]
}
]
}';
// decode your json into associative arrays
$decoded = json_decode($json, true);
// use array
echo "Username: ". $decoded['user_name'] . "<br>";
echo "Date: ". $decoded['selected_date'] . "<br>";
echo "project: ". $decoded['selected_project'] . "<br>";
echo "Task: ". $decoded['tasks'][0]['task_name'] . "<br>";
foreach($decoded['tasks'][0]['work_hours'] as $key => $value) {
foreach($value as $key2 => $value2){
echo $key2 . ": ". $value2 . "<br>";
}
}
?>