来自sql

时间:2018-04-16 10:01:30

标签: php sql arrays array-sum

我对php很新,所以我正在寻找一些方向。我是查询SQL服务器,我需要在一些列上做一笔总和。如果我使用的数组1,2,3有效,但我似乎无法获得impressions_total的值。

$sql = "SELECT * FROM dash_g_adwords_csv";
$stmt = sqlsrv_query($conn, $sql);
if( $stmt === false) {
   die( print_r( sqlsrv_errors(), true) );
}

//while($row = sqlsrv_fetch_rows($stmt)){
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_BOTH) ) {
   //print_r($row);
   $impressions_total = array('impressions_total', 'impressions_image', 'impressions_search'); 
   //$impressions_total = array(1, 2, 3); 
   //$click_total = array('$click_text', '$click_image', '$click_search');

   echo
   "<tr><td>" . $row['brand'] .
   "</td><td>" . $row['period'] .
   "</td><td>" . array_sum($impressions_total) .
   "</td><td>" . array_sum['$click_total'] .
   "</td></tr>";
}
sqlsrv_free_stmt( $stmt);

2 个答案:

答案 0 :(得分:1)

 $impressions_total = array('impressions_total', 'impressions_image', 'impressions_search'); 

此LOC使您的impressions_total成为字符串数组,而不是整数或数字数组。

array_sum 

仅适用于数组数组。

答案 1 :(得分:1)

您尝试对不起作用的字符串数组求和!

您似乎想要总结展示次数和点击次数。所以你可以使用以下内容:

while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_BOTH)) {
    $impressions_total = [$row['impressions_total'], $row['impressions_image'], $row['impressions_search']];
    $click_total = [$row['click_text'], $row['click_image'], $row['click_search']];

   echo
   "<tr><td>" . $row['brand'] .
   "</td><td>" . $row['period'] .
   "</td><td>" . array_sum($impressions_total) .
   "</td><td>" . array_sum($click_total) .
   "</td></tr>";
}