BaseLogic.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. <?php
  2. namespace app\v1\logic\tool;
  3. use support\think\Db;
  4. class BaseLogic
  5. {
  6. protected function replaceData($where): bool
  7. {
  8. // 设置归属人
  9. $this->siteAuth();
  10. // 先删除,再写入
  11. Db::connect('db_data_report')->table($this->table)->where($where)->delete();
  12. // 保持每个子数组键一致,无值则填充0
  13. $insertData = $this->normalizeArrayKeys($this->data);
  14. return Db::connect('db_data_report')->table($this->table)->insertAll($insertData) !== false;
  15. }
  16. protected function pushData($rows): void
  17. {
  18. if ($rows) {
  19. foreach ($rows as $row) {
  20. $groupArr = explode(',', str_replace(' ', '', $this->group));
  21. $uniqueKey = [];
  22. foreach ($groupArr as $groupKey){
  23. $groupKey = trim($groupKey);
  24. $kk = $row[$groupKey] ?? "";
  25. $uniqueKey[] = $kk;
  26. }
  27. $uniqueKey = implode("_", $uniqueKey);
  28. foreach ($row as $k => $v) {
  29. if(in_array($k, $groupArr)){
  30. $this->data[$uniqueKey][$k] = $v;
  31. }else{
  32. $this->data[$uniqueKey][$k] = !empty($this->data[$uniqueKey][$k]) ? $this->data[$uniqueKey][$k] + $v :$v;
  33. }
  34. }
  35. }
  36. }
  37. }
  38. protected function siteAuth(): void
  39. {
  40. $agentList = Db::connect('db_advert')->table("agent_list")->column("id, media_id, auth_id");
  41. $agentListMap = array_column($agentList, null, "id");
  42. if($this->data){
  43. foreach ($this->data as &$item){
  44. $item['auth_id'] = $agentListMap[$item['agent_id']]['auth_id'] ?? 0; // 负责人
  45. $item['media_id'] = $agentListMap[$item['agent_id']]['media_id'] ?? 0; // 媒体
  46. }
  47. }
  48. }
  49. protected function normalizeArrayKeys(array $data): array {
  50. // 收集所有可能的键
  51. $allKeys = [];
  52. foreach ($data as $item) {
  53. $allKeys = array_merge($allKeys, array_keys($item));
  54. }
  55. $allKeys = array_unique($allKeys);
  56. // 标准化每个子数组
  57. $result = [];
  58. foreach ($data as $item) {
  59. $normalizedItem = [];
  60. foreach ($allKeys as $key) {
  61. $normalizedItem[$key] = $item[$key] ?? 0;
  62. }
  63. $result[] = $normalizedItem;
  64. }
  65. return $result;
  66. }
  67. }