2014-06-14 48 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