2014-01-26 65 views
0

我使用下面的代碼來獲取用戶facebook的朋友列表,並對應用數據庫中的用戶進行檢查。此代碼會返回應用的用戶,他們是用戶的Facebook好友。將mysql_query結果傳遞給foreach

 $friends_set = '('; 
      foreach($friends["data"] as $value) { 
       $friends_set .= $value['id'].','; 
      } 
      $new_set = preg_replace('/,$/',')',$friends_set); 
       $res = mysql_query("SELECT * from user AS u, upload AS up WHERE u.fb_id IN $new_set AND u.fb_id=up.user_id") or die(mysql_error()); 

    while($row = mysql_fetch_array($res)) { 

     echo $row['fb_id']. "". $row['first_name']; 
     echo "<br>"; 

     } 

$data['top_friends']=$res; 
$this->load->view('myview'); 

此代碼有效。它位於我的codeigniter應用程序的控制器中,並將正確的數據成功回顯到頁面上。

但是現在我需要打印查詢的結果,在爲每個語句在我看來是這樣的:當我嘗試使用每個沒有關係得到查詢結果視圖

<?php foreach ($top_friends as $me) : ?> 

        <div > 

        <p><?php echo $me['first_name']; ?></p> 

        <?php endforeach; ?> 

然而沒有工作。

我該如何解決這個問題?

回答

1

你可以試試codeignitor的方式,創建一個模型函數說get_top_friends,我假設你傳遞一個逗號分隔的字符串作爲參數,如$ fb_id = '45,65,78,89'。說facebook_model是模型的那麼名稱:

class Facebook_model extends CI_Model{ 
    //other functions and constrcutor here 

    //function to get the top friends 
    function get_top_friends($fb_id){ 
     $fbId = explode(",",$fb_id) 
     $this->db->select('*'); 
     $this->db->where_in('fb_id',$fbId); 
     $this->db->order_by('points','desc'); 
     $this->db->limit(10); 
     $query = $this->db->get('user'); 
     if ($query->num_rows() < 1) return FALSE; 
     return $query->result_array(); 
    } 
} 

,並在你的代碼如下變化:

$friends_set = ''; 
    foreach($friends["data"] as $value) { 
     $friends_set .= $value['id'].','; 
    } 
    $new_set = preg_replace('/,$/',')',$friends_set); 
    $res = $this->facebook_model->get_top_friends($new_set); 
    $data['top_friends']=$res; 
    $this->load->view('myview',$data); 

現在考慮可以嘗試

foreach ($top_friends as $me){ 
    echo $me['first_name']; 
} 

[更新了用戶]

如果你想這樣做你的問題:然後嘗試,

$result = array(); 
while($row = mysql_fetch_array($res)) { 
     $result[] = $row; 
} 
$data['top_friends']=$result; 
$this->load->view('myview',$data);//pass data to view 
+0

請參閱對問題的編輯。以前的查詢沒有正確返回,上面的查詢沒有正確返回。對於每一個仍然可以用這種方式工作? – Tester

+0

已更新答案 –

+0

好的,謝謝你會嘗試。另外,我試圖在我的問題中將查詢用作具有活動記錄的模型函數,因爲我需要設置'$ this-> db-> limit($ limit,$ start);'爲結果分頁。或者我將如何在控制器中設置當前的mysql查詢?其中$ limit是$ config [「per_page」],並且$ start是$ this-> uri-> segment(3) – Tester