-2
Well I am mounting an array with a query that comes from PDO it is giving me the result I want, but I do not know if this is the best way to do it.
Follow my php code:
// Array com os dados
$consulta[] = array('Cod' => 10, 'DataOp' => '2020-06-08', 'ValorOp' => 10);
$consulta[] = array('Cod' => 11, 'DataOp' => '2020-06-09', 'ValorOp' => 15);
$consulta[] = array('Cod' => 12, 'DataOp' => '2020-06-08', 'ValorOp' => 90);
$consulta[] = array('Cod' => 13, 'DataOp' => '2020-06-11', 'ValorOp' => 78);
// Inicia variáveis
$listaBruta = array();
$listaData = array();
$lista = array();
// Monta a lista
foreach ($consulta as $linha) {
$listaBruta[] = $linha;
// Verifica se já existe a data no array
if (!in_array($linha['DataOp'], $listaData)) {
$listaData[] = $linha['DataOp'];
}
}
// Monta lista agrupada
foreach ($listaData as $linha) {
// Inicia variáveis
$listaFiltrada = array();
// Filtra o array
foreach ($listaBruta as $operacao) {
// Verifica se a data é igual
if ($linha === $operacao['DataOp']) {
$listaFiltrada[] = array(
"cod" => (int) $operacao['Cod'],
"valorOp" => (float) $operacao['ValorOp']
);
}
}
$lista[] = array(
"dataOp" => $linha,
"operacoes" => $listaFiltrada
);
}
echo json_encode($lista, 256);
The answer I have is this, it’s the way I want it.
[
{
"dataOp": "2020-06-08",
"operacoes": [
{
"cod": 10,
"valorOp": 10
},
{
"cod": 12,
"valorOp": 90
}
]
},
{
"dataOp": "2020-06-09",
"operacoes": [
{
"cod": 11,
"valorOp": 15
}
]
},
{
"dataOp": "2020-06-11",
"operacoes": [
{
"cod": 13,
"valorOp": 78
}
]
}
]
So I guess you answered me while I was editing my question. Your example ended up getting more complex than, what I used. And you didn’t document it, it got hard to understand.
– Hugo Borges
@Hugoborges sorry for not having documented, I will be but next answer , you could post your answer I was curious how you did
– clone por
I edited my question to be more complete, and there I put as I did. Check there and tell me what you think.
– Hugo Borges
@Hugoborges a yes I found it cool , I noticed that they repeat themselves dubbing the same array I think it would be to use array_filter(), to erase the same, I followed your advice and put the comments explaining what each thing does, you a read and see if it is better to understand
– clone por
Show, now I could understand your logic better. Taking advantage of gave a analyzed in the bug you commented. I opted for a different approach, instead of removing the duplicities I used the function
in_array
so I check if the value already exists in the array, and only then add it. So I avoid duplicates. I edited my question with this change.– Hugo Borges