Nodoid Nodoid - 17 days ago 4
JSON Question

Obtaining all instances of a specific field from json in PHP

I have a webservice that returns a very large json object. I decode this to an array for parsing.

What I'm trying to do though is extract all array members from the json array where there is [id] => 21 at the start of the individual array object.

A nice simple task using LINQ, but not an idea how to do this in PHP. There has to be a way to filter through and extract.

Answer

I'd use something like array_filter for this

function find_id($var)
{
    // returns whether the is is 21
    return($var['id'] === 21);
}


$result = array_filter($jsondata, "find_id"));

array_filter Iterates over each value in the array passing them to the callback function. If the callback function returns true, the current value from array is returned into the result array. Array keys are preserved.