Estoy realizando una consulta a mi base de datos para mostrar el contenido en una tabla de una pagina web php. Quiero mostrar dos tablas, una con ingresos y otra con gastos. Tengo el siguiente código, en el que para hacer esto, he duplicado el código que crea la tabla.
Dejo el código php
:
<html lang="en">
<head>
<title>Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<?php
$link = new PDO('mysql: host=localhost; dbname=personal','root','admin');
?>
<table class="table table-hover">
<thead>
<tr style="background-color:grey; border-bottom: 3px solid black;">
<th>DATE</th>
<th>AMOUNT</th>
<th>CONCEPT</th>
<th>OPERATION</th>
</tr>
</thead>
<?php foreach ($link->query('SELECT * from cashflow where operation="IN"') as $row){ ?>
<tr>
<td><?php echo $row['operation_date'] ?></td>
<td><?php echo $row['amount'] ?> €</td>
<td><?php echo $row['entity'] ?></td>
<td><?php echo "INCOME" ?></td>
</tr>
<?php
}
?>
</table>
<table class="table table-hover">
<thead>
<tr style="background-color:grey; border-bottom: 3px solid black;">
<th>DATE</th>
<th>AMOUNT</th>
<th>CONCEPT</th>
<th>OPERATION</th>
</tr>
</thead>
<?php foreach ($link->query('SELECT * from cashflow where operation="OUT"') as $row){ ?>
<tr>
<td><?php echo $row['operation_date'] ?></td>
<td><?php echo $row['amount'] ?> €</td>
<td><?php echo $row['entity'] ?></td>
<td><?php echo "SPENDING" ?></td>
</tr>
<?php
}
?>
</table>
</body>
</html>
Mi pregunta es si esto se puede "simplificar" para hacer el código más sencillo sin duplicar tanto.
¡Gracias de antemano!
foreach( ['IN','OUT'] as $op ){
.operation
, incluso creando un objeto más o menos así desde la misma consulta:{"IN":[{"operation_date":"unaFecha","amount":"999","entity":"abc"},{"operation_date":"unaFecha","amount":"999","entity":"abc"}],"OUT":[{"operation_date":"unaFecha","amount":"999","entity":"abc"},{"operation_date":"unaFecha","amount":"999","entity":"abc"}]}
y luego leerlo como un JSON.