2012-06-15 92 views
0

我在這裏是一個PHP頁面與Facebook API一起工作。Randomize/Shuffle數組,然後foreach,然後限制到10個結果(Facebook API + PHP)

我想要做的是(在權限由用戶設置後),通過$facebook->api('/me/friends')獲取用戶的朋友的用戶ID。問題是,我只想得到隨機10位朋友。我可以很容易地通過使用/me/friends?limit=10將結果限制爲10,但是再次這不會是隨機的。

所以這是我現在所擁有的:

 $friendsLists = $facebook->api('/me/friends'); 

    function getFriends($friendsLists){ 
     foreach ($friendsLists as $friends) { 
      foreach ($friends as $friend) { 
      // do something with the friend, but you only have id and name 
      $id = $friend['id']; 
      $name = $friend['name']; 
     shuffle($id); 
    return "@[".$id.":0],"; 
      } 
     } 
    } 

$friendsies = getFriends($friendsLists); 
$message = 'I found this Cover at <3 '.$Link.' 

'.$friendsies.' check it out! :)'; 

我試圖洗牌(),並從這裏第一個選項:https://stackoverflow.com/a/1656983/1399030,但我認爲因爲他們沒有我做錯了什麼回報什麼。我很確定我很近,但我迄今爲止嘗試過的方法並不奏效。可以做到嗎?

+0

的可能重複[Facebook的圖形API:獲得一個隨機N的朋友(http://stackoverflow.com/questions/8570459/facebook -graph-api-getting-a-random-n-friends) –

+0

@EvanMulawski希望沒有使用FQL查詢。由於我已經有了friendslist數組,我只需要知道一種方法來洗牌。 – Mafia

回答

1

你想在foreach之前使用shuffle,以便你實際上洗牌數組。

之後,你會想限制爲10個朋友。我建議添加一個$我的變種數到十,並添加到一個新的數組。

事情是這樣的:

function getFriends($friendsLists){ 
    $formatted_friends = array(); 
    $i = 0; 
    foreach ($friendsLists as $friends) { 
     // I'm guessing we'll need to shuffle here, but might also be before the previous foreach 
     shuffle($friends); 
     foreach ($friends as $friend) { 
     // do something with the friend, but you only have id and name 
     // add friend as one of the ten 
     $formatted_friends[$i] = $friend; 
     // keep track of the count 
     $i++; 
     // once we hit 10 friends, return the result in an array 
     if ($i == 10){ return $formatted_friends; } 
     } 
    } 
} 

記住,雖然,它會返回一個數組,而不是您可以在回聲使用字符串。如果你願意,你可以把這個回聲調試目的:

echo 'friends: '.print_r($friendsies, true); 
+0

謝謝@Greg!我只是希望能夠得到這些ID,就像我在當前代碼中它是如何分開名稱和ID一樣,然後我可以使用這些ID – Mafia

+0

您好格雷格,用另一個函數就像我原來的那個一樣,只是這樣我才能分解代碼的結果,以便在洗牌後得到ID。所以我通過另一個foreach函數來運行它,但這對我來說並不是很好。我返回單詞「數組」,但我想通過我的原始函數運行它,它會打破這個數組,顯然我更無知,我認爲。 – Mafia

+1

更改此部分以獲取ID: $ formatted_friends [$ i] = $ friend; 至: $ formatted_friends [$ i] = $ friend ['id'] ;.當您嘗試回顯某個數組時,會出現數組字樣。如果你在嚴格模式下使用PHP,它也會拋出警告(因爲數組不能被回顯)。如果你仍然想回顯,你可以像我向你展示的那樣使用print_r(),或者爲了更高級的格式,你可以嘗試一個implode($ friendsies,',')來得到逗號分隔的結果。我想盡管如果你使用朋友ID來完成其他功能,你可能想保留一個數組。 – Greg

相關問題