2015-09-15 88 views
1

我正在學習php。PHP foreach功能

我有一個mysql查詢選擇功能。

比我用foreach列表中使用它..

但只有在foreach是在函數內部它的工作我。 我不知道如何讓它在功能之外工作..

我做錯了什麼?

工作代碼 - https://phpbox.info/d3GCP

沒有工作代碼:

function volaco() 
{ 
$query = $db->getQuery(true); 

$query = "select a.id, count(i.id) as all_items, a.name, SUM(i.state = '1') published, SUM(i.state = '0') unpublished" 
    . " FROM item as i" 
    . " JOIN application a ON a.id = i.application_id" 
    . " group by i.application_id"; 

$db->setQuery($query); 

$apps= $db->loadObjectList(); 

} 

$apps = volaco(); 
?> 

    <table > 
     <?php if (count($apps)) : foreach ($apps as $app) : ?> 
      <tr > 
       <td width="40%"><?php echo $app->name; ?></td> 
       <td width="20%" style="text-align: center;"><?php echo $app->all_items;?></td> 
       <td width="20%" style="text-align: center;"><?php echo $app->published; ?></td> 
       <td width="20%" style="text-align: center;"><?php echo $app->unpublished; ?></td> 
      </tr> 
     <?php endforeach; else : ?> 
<?php endif; ?> 
    </table> 

非常感謝

+1

你需要** **回報你在函數返回 – Rizier123

+0

結果變量組成的函數,那麼你可以把它像$應用= volaco(); – Akshay

回答

1

功能,您需要volaco()返回類型

return $apps= $db->loadObjectList(); 

Returning values

0

添加返回到您的volaco()函數,$ apps不在範圍內。

function volaco() 
     { 
     $query = $db->getQuery(true); 

     $query = "select a.id, count(i.id) as all_items, a.name, SUM(i.state = '1') published, SUM(i.state = '0') unpublished" 
      . " FROM item as i" 
      . " JOIN application a ON a.id = i.application_id" 
      . " group by i.application_id"; 

     $db->setQuery($query); 

     return $db->loadObjectList(); 
     ?> 
0

試試這個:

function volaco() 
{ 
$query = $db->getQuery(true); 

$query = "select a.id, count(i.id) as all_items, a.name, SUM(i.state = '1') published, SUM(i.state = '0') unpublished" 
    . " FROM item as i" 
    . " JOIN application a ON a.id = i.application_id" 
    . " group by i.application_id"; 

$db->setQuery($query); 

$apps= $db->loadObjectList(); 
return $apps; 

} 

$apps = volaco(); 
?> 

    <table > 
     <?php if (count($apps)) : foreach ($apps as $app) : ?> 
      <tr > 
       <td width="40%"><?php echo $app->name; ?></td> 
       <td width="20%" style="text-align: center;"><?php echo $app->all_items;?></td> 
       <td width="20%" style="text-align: center;"><?php echo $app->published; ?></td> 
       <td width="20%" style="text-align: center;"><?php echo $app->unpublished; ?></td> 
      </tr> 
     <?php endforeach; else : ?> 
<?php endif; ?> 
    </table>