开发者

iterating through a changeable JSON array

I'm working on a web application that takes its data from a web page using the Yahoo Query Language API to return a JSON array. I've hit a block in that sometimes, when there is only one "race" on the page, the array is setup differently and I can't iterate through it in some circumstances. Let me explain in an example.

Array layout for a page with mutiple races

Array (
    [div] => array (
        [0] => array (
            ['venue_id'] = 02222
            ['venue_name'] = 'Hove'
            ['race_id'] = 9222
        )
        [1] => array (
            ['venue_id'] = 03333
            ['venue_name'] = 'Romford'
            ['race_id'] = 2442
        )
        //...and so on
    )
)

Array layout for a page with just one race

Array (
    [div] => array (
        ['venue_开发者_如何学运维id'] = 02222
        ['venue_name'] = 'Hove'
        ['race_id'] = 9222
    )
)

In the application, I'm currently using a simple foreach statement to iterate through the array. However, this obviously wont work with the second example and I need a workaround.

Example of foreach statement

foreach($result['div'] as $race) {
    echo 'Venue ID: '.$race['venue_id'];
    echo 'Venue Name: '.$race['venue_name'];
    echo 'Race ID: '.$race['race_id'];
}

Any help would be massively appreciated!

Dan


I'd do this..

if(!isset($array['div'][0])) $array['div'] = array($array['div']);

This way I do not have to have two iteration methods.


Take a look at the count value which is returned with all YQL result sets. If there is only one result, then force it to be an array (with one item) just like when there are multiple results.

So, something like…

if ($yql['query']['count'] == 1) {
    $yql['results']['data'] = array($yql['results']['data']);
}

This way, the rest of your script doesn't need to care about the structure of the results.


What about:

if ( isset($result['div'][0])){
     //first iteration method
} else{
    //second iteration method
}


As simple as:

function format_race($race) {
    echo 'Venue ID: '.$race['venue_id'];
    echo 'Venue Name: '.$race['venue_name'];
    echo 'Race ID: '.$race['race_id']  
}
if (isset($result['div']['venue_id'])) {
    format_race($result);
} else {
    array_map('format_race', $result);
}

This also has the advantage of abstracting the data manipulation in an external function, which can come handy in many situations.

Please note that here I'm abusing a little of array_map, probably using foreach($result as $race) would make your program more readable for other php programmers if all you have to do is just printing.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜