在PHP中循环两个查询数组和ECHO

时间:2017-09-01 19:44:34

标签: php arrays json echo

$query = "
 SELECT SUM(KDV_Haric_Ciro) AS Ciro , Donem
                    FROM general_Table
                    Where EczaneID = '".$pharmacy_id."' AND Yil = '".$dateYear."'
                    GROUP BY Donem";
$result = mysqli_query($link, $query );

$queryTwo = "
 SELECT SUM(KDV_Haric_Ciro) AS Ciro, Donem
                    FROM general_Table
                    Where EczaneID = '".$pharmacy_id."' AND Yil = '".$dateLastYear."'
                    GROUP BY Donem";
$resultTwo = mysqli_query($link, $queryTwo );

// Print out rows
$prefix = '';
echo "[\n";
while ( ??? //$rowTwo = mysqli_fetch_assoc( $resultTwo ) -> loops through only 1 array
) {
    $row = mysqli_fetch_assoc( $resultTwo )
  echo $prefix . " {\n";
  echo '  "month": "' . $rowTwo["Donem"] . '",' . "\n";
  echo '  "ciro": ' . $row["Ciro"]. '' . "\n";
  echo '  "ciroLastYear": ' . $rowTwo["Ciro"]. '' . "\n";
  echo " }";
  $prefix = ",\n";
}
echo "\n]";

所以基本上我在fson中的fetchind数据为另一个api,但我需要在同一个循环中回显两个数据我已经尝试过很多东西你可以填充(???)部分以便我可以

2 个答案:

答案 0 :(得分:1)

您是否考虑过重写SQL以便一次性提取数据?

SELECT donem,
       SUM(CASE WHEN yil IN ('2016') then kdv_haric_ciro) AS prior_year,
       SUM(CASE WHEN yil IN ('2017') then kdv_haric_ciro) AS current_year       
  FROM general_table
 WHERE eczaneid = '".$pharmacy_id."'
 GROUP BY donem

现在,您不必遍历两个不同的查询,只需遍历一个结果集并将其格式化为API调用。

答案 1 :(得分:0)

最终看起来您的查询可以调整为使用OR添加其他条件。然后你有一个查询,一个结果集循环。您需要使用括号对条件集进行分组。

$query = "
  SELECT SUM(KDV_Haric_Ciro) AS Ciro , Donem
  FROM general_Table
  Where (EczaneID = '".$pharmacy_id."') 
  AND (Yil = '".$dateYear."' OR Yil = '".$dateLastYear."')
  GROUP BY Donem";

$result = mysqli_query($link, $query );

// Print out rows
$prefix = '';
echo "[\n";
while ($row = mysqli_fetch_assoc($result)) {
  $row = mysqli_fetch_assoc($result)
  echo $prefix . " {\n";
  echo '  "month": "' . $row["Donem"] . '",' . "\n";
  echo '  "ciro": ' . $row["Ciro"]. '' . "\n";
  echo '  "ciroLastYear": ' . $row["Ciro"]. '' . "\n";
  echo " }";
  $prefix = ",\n";
}
echo "\n]";

有关详情,请参阅https://dev.mysql.com/doc/refman/5.7/en/where-optimization.html