2014-06-14 49 views
-2

我在控制器中遇到有關heredoc語法的問題。我的控制器的功能是這樣的:如何在foreach循環中使用php heredoc語法

function active() { 
    $userlist = $this->input->post('userlist'); 
    $userlist = explode(',',$userlist[0]); 

    $items = ''; 

    if(!empty($userlist)){ 
     foreach($userlist as $buddy) 
     { 

      $actv = $this->user_model->check_active_users($buddy);//returns 0 if no results found 
      if ($online_buddies == 0) { 
       $items .= <<<EOD 
      { 
       "fl": "0", 
       "fid": "{$buddy}" 
      }, 
EOD; 
      }//if returned 0 inactive 

     }//foreach 
    }//if nt empty $mybuddies 

    if ($items != '') 
    { 
     $items = substr($items, 0, -1); 
    } 
    header('Content-type: application/json'); 
?> 
{ 
    "items": [ 
     <?php echo $items;?> 
    ] 
} 

<?php 
     exit(0); 

}//end of func active 

$userlist持有user-ids

$this->user_model->check_active_users($buddy)如果找不到結果,則返回0。

我想得到一個標誌0如果在數據庫中找不到任何結果以及相應的用戶標識符。

但是,

$items .= <<<EOD 
{ 
"fl": "0", 
"fid": "{$buddy}" 
} 
EOD; 

這裏,fl回報0fid將返回什麼。我做錯了嗎?"fid": "{$buddy}"

+0

,而不是操作字符串,你應該嘗試使用PHP本身的數組S和輸出最終結果由'json_encode()'; –

+0

坦克很多..... – user3177114

回答

0

heredoc好像對你正在創建的內容有點多。那麼,爲什麼不去做這樣的事情,而不是:

$items .= '{ 
      "fl": "0", 
      "fid": "' . $buddy . '" 
      },' 
1
$html = <<<HTML // Set a variable for your dashboard HTML 

HTML here... 

HTML; // This ends the heredoc for now and concludes the HTML to open the PHP back up 

// The follow resumes your pure PHP code 
$query = "SELECT * FROM `some_table_in_database`"; 

$results = mysqli_query($query); 


foreach ($results as $record) { 

    // Bellow you define the records as variables 

    $variable1   = $record->one; 
    $variable2   = $record->two; 
    // as many variables as you would like 

    $html .= <<<HTML // Now, you have to concatenate to your $html variable (adding on to it) some more HTML 

    HTML here.... 

HTML; // Now we need to switch back over to PHP, so we close the HTML for now 

    // Begin more PHP code here for further use down the page 

    $html .= <<<HTML // We open back up the HTML variable to put more HTML in our page 

    HTML here... 

HTML; // and this concludes the HTML. You can keep going on for ever like this alternating between PHP and HTML code in order to get for and foreach loops and such to cooperate. 
+0

我的上面的代碼從堆棧溢出代碼突出顯示器中分解了一下,但<<< SUPPLIERDASHBOARD heredoc opener和SUPPLIERDASHBOARD;更接近你想要關注的部分。注意它們是如何連接的。在PHP腳本週圍仔細分解它們,並在HTML大塊中使用它們。 – mrwpress