teratail header banner
teratail header banner
質問するログイン新規登録

回答編集履歴

1

修正

2019/03/11 05:34

投稿

papinianus
papinianus

スコア12705

answer CHANGED
@@ -1,5 +1,7 @@
1
- バグ原因は分かりません、$arrShopSales作りかと代入が変な気がする
1
+ 変数誤記などあったで、全部書き換えしました。
2
+ 質問者様のコメントは、foreachの行の最後が:ではなく;になっているため、foreachの中で何もしないことにされており、htmlのテーブルがループせずに、foreachの最後の値だけが出力されていた、という現象だと思います。
2
3
  ```php
4
+ <?php
3
5
  $arrShopSales = [];
4
6
  $months = ["1月","2月","3月",];
5
7
  $shops = ["A", "B"];
@@ -9,14 +11,58 @@
9
11
  $arrShopSales[$month][$shop] = ["product_count"=>0, "sales"=>0];
10
12
  }
11
13
  }
14
+
15
+
16
+ $file =<<<EOF
17
+ 1月,A,123,345
18
+ 2月,B,23,67
19
+ 1月,B,111,765
20
+ 3月,B,435,1234
21
+ 2月,A,341,987
22
+ 1月,B,453,900
23
+ 1月,A,231,700
24
+ 2月,B,122,499
25
+ 2月,A,567,1345
26
+ 3月,A,879,2300
27
+ EOF;
28
+ $file = explode("\n", $file);
29
+
12
30
  //↓こう使う
13
31
  foreach($file as $res) {
32
+ $res = explode(",", $res);
14
33
  if ($res[0] === null) continue;
15
34
  $month = $res[0];
16
35
  $place = $res[1];
17
36
 
18
- $arrShopSales[$month][$shop]['product_count'] += $res[2];
37
+ $arrShopSales[$month][$place]['product_count'] += $res[2];
19
- $arrShopSales[$month][$shop]['product_count'] += $res[3];
38
+ $arrShopSales[$month][$place]['sales'] += $res[3];
20
39
  }
40
+ ?>
41
+
42
+ <table border="1">
43
+ <tr>
44
+ <th>月</th>
45
+ <th>店舗</th>
46
+ <th>売上商品数</th>
47
+ <th>売上(千円)</th>
48
+ </tr>
49
+ <?php foreach($arrShopSales as $month => $shopSaleData): ?>
50
+ <tr>
51
+ <td rowspan="2">
52
+ <?php echo $month; ?>
53
+ </td>
54
+ <?php foreach($shopSaleData as $shop => $sale): ?>
55
+ <td>
56
+ <?php echo $shop; ?>
57
+ </td>
58
+ <td>
59
+ <?php echo $sale['product_count']; ?>
60
+ </td>
61
+ <td>
62
+ <?php echo $sale['sales']; ?>
63
+ </td>
64
+ </tr>
65
+ <?php endforeach;?>
66
+ <?php endforeach;?>
67
+ </table>
21
- ```
68
+ ```
22
- 出力はかえなくても↑に合ってる気がする