开发者

php api associative array

I'm trying to loop through an api call very quickly but I'm seeing very odd behavior with the following loop (doesn't loop through the entire array....writes only 1 or 2 records):

Any ideas:

$i = 0;
foreach($userfriends as $key => $value) {

    if($key == "id"){
    $friend_id = $value;        
    }

    try {
    $username = $friend_id;
    $uservar = '/'.$username.'/likes?fields=id,category&limit=20';
    $userlikes = $facebook->api($uservar);
    }         

    catch (FacebookApiException $e) {
    error_log($e);
    }


    $id = $userlikes[data][$i][id];
    $cat = $userlikes[data][$i][category];


    // WRITING FRIEND LIKES TO DATABASE

    $sql="INSERT INTO likes (like_id, category, friend_id) VALUES ('$id', '$cat', '$friend_id');";
    mysql_query($sql,$con);



$i++;
}

The array userfriends looks like this:

Array
(
    [data] => Array
        (
            [0] => Array
                (
                    [id] => 123123
                )

            [1] => Array
                (
                    [id] => 456456
                )

            [2] => Array
                (
开发者_如何学Go                    [id] => 634476
                )


foreach only loops through the first level of any given array. What you have presented is in fact arrays nested within other arrays. Given the array in your example, $key will never be equal to "id". If the array will always be structured exactly as given, you should access "id" like this:

foreach($userfriends as $key=>$value) {
    $friend_id = $value['id'];
}

EDIT actually, it's a little more complex than this... I just noticed the array is even more nested than I first thought, which means you must have a level of looping for each level of nesting. If I'm seeing the whole array, it might start like this:

foreach($userfriends['data'] as $key=>$value {

assuming all we're interested is what's in the "data" associative array...

If you don't know how deeply nested the array will be, and you really need to extract only the "id" field wherever it is, the easiest way to handle it would be a recursive function with a contained loop. But that's a whole other topic...


Shouldn't it be

$i = 0; foreach($userfriends['data'] as $key => $value) {
/* YOUR STUFF */
$i++;
}

Edit

Full code

$i = 0;
foreach($userfriends['data'] as $key => $value) {

if($key == "id"){
$friend_id = $value;        
}

try {
$username = $friend_id;
$uservar = '/'.$username.'/likes?fields=id,category&limit=20';
$userlikes = $facebook->api($uservar);
}         

catch (FacebookApiException $e) {
error_log($e);
}


$id = $userlikes[data][$i][id];
$cat = $userlikes[data][$i][category];


// WRITING FRIEND LIKES TO DATABASE

$sql="INSERT INTO likes (like_id, category, friend_id) VALUES ('$id', '$cat', '$friend_id');";
mysql_query($sql,$con);



$i++;
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜