-2

I am working on an exam system and I have run into a problem for getting the right result. I want this result from answers array which match question ID 466

(
[id] => 234
[firstChoice] => 2
[choice] => 2
[marked] => 
[strikethrough] => Array()
[highlights] => 
[guessed] => 
[difficulty] => easy
[numTimesChanged] => 
[timeElapsed] => 36
)

I have this type of answers std class array. I have same type of array for questions too.

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
    )
)
Nasirsom
  • 11
  • 2

2 Answers2

0

Try this:

$result = null;
foreach($array as $value){
    if($value->id == 466){
        $result = $value;
        break;
    }
}
Julian Kuchlbauer
  • 865
  • 1
  • 8
  • 16
0

In the case of your ID is not unique, you can use array_filter()

Solution :

<?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

Jean B.
  • 176
  • 6