我正在开发一个考试系统,遇到了一个获得正确结果的问题。我想从与问题ID 466 匹配的答案数组中得到这个结果
(
[id] => 234
[firstChoice] => 2
[choice] => 2
[marked] =>
[strikethrough] => Array()
[highlights] =>
[guessed] =>
[difficulty] => easy
[numTimesChanged] =>
[timeElapsed] => 36
)
我有这种类型的答案std类数组。我也有同样类型的问题数组。
Array(
[0] => stdClass Object
(
[id] => 234
[firstChoice] => 2
[choice] => 2
[marked] =>
[strikethrough] => Array
(
)
[highlights] =>
[guessed] =>
[difficulty] => easy
[numTimesChanged] =>
[timeElapsed] => 36
)
[1] => stdClass Object
(
[id] => 466
[firstChoice] => 3
[choice] => 3
[marked] =>
[strikethrough] => Array
(
)
[highlights] =>
[guessed] =>
[difficulty] => easy
[numTimesChanged] =>
[timeElapsed] => 5
)
)
试试这个:
$result = null;
foreach($array as $value){
if($value->id == 466){
$result = $value;
break;
}
}
如果您的ID不是唯一的,您可以使用array_filter()
解决方案:
<?php
$array = json_decode('[{"id":4,"data":"data1"},{"id":14,"data":"data41"},{"id":14,"data":"data14"}]');
$idSearched = 14;
function filter($item){
global $idSearched;
return $item->id === $idSearched;
}
$res = array_filter($array, "filter");
print_r($res);
实例