php与mysql表中如何求递归求和汇总?

php与mysql表中如何求递归求和汇总?,第1张

function sumShuzi(&$tree, &$updateData = array()) {

  $sum = 0

  // foreach($tree as $key => $item) {  //这句话有毒

  foreach($tree as $key => &$item) {

    if(isset($item['children'])) {

      $oldPshuzi = $tree[$key]['Pshuzi']

      $tree[$key]['Pshuzi'] = sumShuzi($item['children'], $updateData)

      if($oldPshuzi != $tree[$key]['Pshuzi']) {

        $updateData[$item['id']] = array($tree[$key]['Pshuzi'], $tree[$key]['Pname_ch'])

      }

    }

    $sum += $tree[$key]['Pshuzi']

  }

  return $sum

}

$tree = json_decode('[{"id":"1","Pid":"0","Pname_ch":"\u6e20\u9053\u90e8","Pshuzi":"1638000","children":[{"id":"4","Pid":"1","Pname_ch":"\u9500\u552e\u4e8c\u90e8","Pshuzi":"895000","children":[{"id":"13","Pid":"4","Pname_ch":"\u5468\u7ecf\u7406","Pshuzi":"28","children":[{"id":"28","Pid":"13","Pname_ch":"\u6e56\u5357","Pshuzi":"158000"},{"id":"35","Pid":"13","Pname_ch":"\u65b0\u7586","Pshuzi":"19000"}]},{"id":"40","Pid":"4","Pname_ch":"\u9648\u7ecf\u7406","Pshuzi":"5000"}]}]}]', true)

//$tree是具有父子关系的数据

sumShuzi($tree, $updateData)

foreach ($updateData as $id => $item) {

  $sql = "update your_table set Pshuzi={$item[0]} where id={$id}"

  mysqli_query($db, $sql)    //$db是你的数据库连接结果

}

使用UNION

select DEPT_NAME, USER_NAME, PHONE, CONTENT, SEND_TIME from sms3

UNION ALL

select DEPT_NAME,SENDER_NAME,MOBIL_NO ,CONTENT,DIA_TIME from diary

在每个select 语句中可以使用where 条件指定数据

两个表的对应列类型最好一致

SELECT ...

UNION [ALL | DISTINCT] SELECT ...

[UNION [ALL | DISTINCT] SELECT ...]

UNION is used to combine the result from multiple SELECT statements into a single result set.

The column names from the first SELECT statement are used as the column names for the results returned. Selected columns listed in corresponding positions of each SELECT statement should have the same data type. (For example, the first column selected by the first statement should have the same type as the first column selected by the other statements.)


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/8636169.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-04-19
下一篇 2023-04-19

发表评论

登录后才能评论

评论列表(0条)

保存