1

I am pulling data from a json and decoding it via json_decode. Here is the code I am using:

$jsonurl = "http://ebird.org/ws1.1/data/obs/geo/recent?lng=-76.51&lat=42.46&dist=2&back=1&maxResults=500&locale=en_US&fmt=json&includeProvisional=true";
$json = file_get_contents($jsonurl);
$json_output = json_decode($json);

This gives results the results in the format:

Array ( [0] => stdClass Object ( [comName] => House Sparrow [howMany] => 2 [lat] => 42.4613266 [lng] => -76.5059255 [locID] => L99381 [locName] => Stewart Park [locationPrivate] => [obsDt] => 2012-02-28 08:26 [obsReviewed] => [obsValid] => 1 [sciName] => Passer domesticus ) [1] => stdClass Object ( [comName] => Common Merganser [howMany] => 7 [lat] => 42.4613266 [lng] => -76.5059255 [locID] => L99381 [locName] => Stewart Park [locationPrivate] => [obsDt] => 2012-02-28 08:26 [obsReviewed] => [obsValid] => 1 [sciName] => Mergus merganser ) [2] => stdClass Object ( [comName] => Herring Gull [howMany] => 100 [lat] => 42.4613266 [lng] => -76.5059255 [locID] => L99381 [locName] => Stewart Park [locationPrivate] => [obsDt] => 2012-02-28 08:26 [obsReviewed] => [obsValid] => 1 [sciName] => Larus argentatus ) )

Now, I have been trying for a few days now to filter based on the comName. How for example could you give an array of only the objects where comName = "House Sparrow"?

I am fairly new to php so if there is a better way to do any of this please let me know. Thanks in advance!

2 Answers 2

8

Using the array_filter function would be easiest:

$houseSparrow = array_filter($json_output, function($obj)
{
    return $obj->comName == "House Sparrow";
});

If you are running an older version of PHP which doesn't support anonymous functions (under PHP 5.3), you'll have to use the following code:

function filterHouseSparrow($obj)
{
    return $obj->comName == "House Sparrow";
}
$houseSparrow = array_filter($json_output, 'filterHouseSparrow');
Sign up to request clarification or add additional context in comments.

1 Comment

Ah thanks Tim! This did it. I wasn't even aware 5.2 to 5.3 would make such a large difference.
0
$house_sparrows = array();
foreach ( $json_output as $class ) {
    if ( $class->comName == 'House Sparrow' ) {
        $house_sparrows[] = $class;
    }
}

Tim Cooper's array_filter answer is superior however.

3 Comments

This is giving me blank output. Nothing broken, but absolutely nothing showing on page or in source.
This is an example bit of code, you need to actually connect the $house_sparrows variable to whatever needs it.
Sorry, forgot to print the array. This answer worked as well. Thanks for helping JohnD.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.