PHPのforeach文でtableの作成をしております。
以下図のように被り項目(Red,Green) をまとめる表を作りたいと考えております。
作り方をご教授いただけないでしょうか。
現在以下でスタックしております。
PHP
1 2 <!-- カラーの被りをなくす --> 3 <?php foreach ($lists as $list) : ?> 4 <?php $colors[] = $list->getColor(); ?> 5 <?php endforeach; ?> 6 <?php $colors1 = array_merge(array_unique($$colors)); ?> 7 8 <table> 9 <tr> 10 <th>Color</th> 11 <th>Things</th> 12 <th>Place</th> 13 </tr> 14 15 <?php foreach ($color1 as $co) : ?> 16 <tr> 17 <td><?php echo $co; ?></td> <!--カラーの表示--> 18 19 <td> 20 <?php foreach ($lists as $list): ?>. <!-- listsは上記図のようなリストを作っています--> 21 <?php if ("$co" == $list->getColor()): ?> 22 <li><?php echo $list->getThings; ?></li> <!--Thingsの表示--> 23 <?php endif; ?> 24 <?php endforeach; ?> 25 </td> 26 27 <td> 28 <?php foreach ($lists as $list): ?> 29 <?php if ("$co" == $list->getColor()): ?> 30 <li><?php echo $list->getPlace(); ?></li><!--Placeの表示--> 31 <?php endif; ?> 32 <?php endforeach; ?> 33 </td> 34 35 </tr> 36 <?php endforeach; ?> 37 </table>
URLリンクを配列に追加
1$data = [ 2 ["color" => "red", "things" => "りんご", "place" => "青森", "url" => "https://www.yahoo.co.jp/"], 3 ["color" => "red", "things" => "信号", "place" => "東京", "url" => "https://www.youtube.com/"], 4 ["color" => "red", "things" => "太陽", "place" => "テキサス", "url" => "https://ja.wikipedia.org/wiki/"], 5 ["color" => "green", "things" => "山", "place" => "山形", "url" => "https://www.amazon.co.jp/"], 6 ["color" => "green", "things" => "森", "place" => "静岡", "url" => "https://www.dazn.com/"], 7 ]; 8 9 $result = array_reduce(array_unique(array_map(function ($x) { 10 return $x["color"]; 11 }, $data)), function ($x, $y) use ($data) { 12 $x[$y] = array_map(function ($x) { 13 unset($x["color"]); 14 return $x; 15 }, array_values(array_filter($data, function ($x) use ($y) { 16 return $x["color"] == $y; 17 }))); 18 return $x; 19 }, []); 20 21 22 print_r($result); 23 print "<table border>\n"; 24 print "<thead>\n<tr><th>color</th><th>things</th><th>place</th></tr>\n</thead>\n"; 25 print "<tbody>\n"; 26 foreach ($result as $color => $vals) { 27 print "<tr>"; 28 print "<td rowspan=\"" . count($vals) . "\">$color</td>"; 29 foreach ($vals as $key => $val) { 30 if ($key > 0) { 31 print "</tr>\n<tr>"; 32 } 33 print "<td>${val["things"]}</td>"; 34 print "<td>${val["place"]}</td>"; 35 } 36 print "</tr>\n"; 37 } 38 print "</tbody>\n"; 39 print "</table>\n";
回答2件
あなたの回答
tips
プレビュー