从std类多维数组php中提取完整数组

时间:2016-08-02 10:55:28

标签: php multidimensional-array stdclass

我正在研究考试系统,但我遇到了一个问题,无法获得正确的结果。 我希望这个结果来自与问题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
    )
)

2 个答案:

答案 0 :(得分:0)

试试这个:

$result = null;
foreach($array as $value){
    if($value->id == 466){
        $result = $value;
        break;
    }
}

答案 1 :(得分:0)

如果您的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);

Live example