我有一个网站,我使用JSON来保存一些数据。
以下是保存数据的方法
{"1":{"english":{"grade":"7","time":"79"},"physics":{"grade":"3","time":"48"}}}
注意:我知道这是一种糟糕的做法,但是当我不是那么庞大时,我就做到了!
1
是user_id
,根据在平台上参加考试的用户的ID进行更改。 english
,physics
是此用户使用的主题。
用户一次可以参加的最多考试时间是json
字符串看起来像{"1":{"english":{"grade":"7","time":"79"},"physics":{"grade":"3","time":"48"},"maths":{"grade":"7","time":"79"},"chemistry":{"grade":"3","time":"48"}}}
首先,我认为这是将结果保存为JSON
字符串
[{"subject":"english","grade":"7","time":"79"}, {"subject":"physics", "grade":"3","time":"48"}}]
我的问题是我想用PHP来处理前者。我已经做了一些剥离字符串,我留下了这个{"english":{"grade":"7","time":"79"},"physics":{"grade":"3","time":"48"}}
我试过这个块
$JSONResult = json_decode($aScore->result);
foreach ($JSONResult as $subjectKey => $aSubject)
{
foreach ($aSubject as $theResult)
{
$userResult = '
Subject: **This is what I've not been able to get**
Grade: '.$theResult->grade.'
Time: '.$theResult->time.'
';
}
}
我尝试$aSubject->subjectKey
从第一个foreach
语句中获取关联键值,但它不起作用
任何帮助?
已添加:请留下有关JSON
字符串存储方式的评论。我很乐意学习。
答案 0 :(得分:2)
你不需要内循环。每个主题只是一个对象,而不是一个数组。主题键只是$subjectKey
,它不是对象的一部分。
$JSONResult = json_decode($aScore->result, true); // to get an associative array rather than objects
foreach ($JSONResult as $subjectKey => $aSubject) {
$userResult = "
Subject: $subjectKey
Grade: {$aSubject['grade']}
Time: {$aSubject['time']}
";
}
答案 1 :(得分:0)
您可以使用json_decode!
它将$JSONResult
从stdClass
更改为associative Array!
这意味着你可以这样做:
$str = '{"1":{"english":{"grade":"7","time":"79"},"physics":{"grade":"3","time":"48"}}}';
$result = json_decode($str, true); // Put "true" in here!
echo "<pre>".print_r($result, true)."</pre>"; // Just for debugging!
哪会输出这个:
Array
(
[1] => Array
(
[english] => Array
(
[grade] => 7
[time] => 79
)
[physics] => Array
(
[grade] => 3
[time] => 48
)
)
)
为了循环它:
foreach ($result as $idx => $exams) {
echo $exams['english']['grade']."<br>";
echo $exams['physics']['grade']."<br>";
}
哪会输出这个:
7
3
不知道包含数组数据(基于上面的例子)
$exams
将是Array
(可能包含任何类型的信息):
Array
(
[english] => Array
(
[grade] => 7
[time] => 79
)
[physics] => Array
(
[grade] => 3
[time] => 48
)
)
如果您想循环浏览$exams
:
foreach ($result as $idx => $exams) {
foreach ($exams as $subject => $info) {
echo $info['grade']."<br>";
}
}
这将产生与上例相同的输出,而无需知道主题名称!