Organizing an array based on a field

Asked

Viewed 64 times

-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
        }
    ]
    }
]

1 answer

0

There was no way I could ask because n I have enough point , I had to give a small change because I did not have the object with the data however and only pass the array to object ve if this meets you case n warns me

 <?php
function arrumar($dados)
    {
        //pegar a lista e remontar ela usando a segunda coluna da array como chave principa
        foreach ($dados as $key => $value) {
            foreach ($value as $k => $v) {

                $resultado[$k][] = $v;
            }
        }
        //verificando quais array tem a data igual
        foreach ($resultado['dataOp'] as $k => $v) {
            if (isset($a[$v])) {
                $a[$v] = $a[$v] . ',' . $k;
            } else {
                $a[$v] = $k;
            }
        }
        //montar a lista
        foreach ($resultado['dataOp'] as $key => $linha) {

            $lista[] = array(
                "data" => $linha,
                "operacoes" => array(
                    "cod" => (int)$resultado['cod'][$key],
                    "valorOp" => (float)$resultado['valorOp'][$key]
                )
            );
        }
        //colocar a data do pedido como chave mestre assim apagando todas as dubicadas e colocando o conteudo da operacoes na array ja existente
        foreach ($a as $k => $v) {
            $explode = explode(',', $v);
            $i = 0;
            if (isset($explode[0])) {
                foreach ($explode as $rk => $vk) {
                    if ($i <> 0) {
                        $listar[$lista[$vk]['data']]['operacoes'] = array_merge([$lista[$keyatual]['operacoes']], [$lista[$vk]['operacoes']]);

                    } else {
                        $keyatual = $vk;
                        $listar[$lista[$vk]['data']] = $lista[$vk];
                    }
                    $i = 1;
                }

            }
        }


        //substituindo o nome da array mastre e colocando numero apara facilitar o usso ficando $operacoes[0] e asiim por diante 
        foreach ($listar as $v) {
            $operacoes[] = $v;
        }

        return $operacoes;
    }
echo json_encode(arrumar($consulta), 256);
?>
  • 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.

  • @Hugoborges sorry for not having documented, I will be but next answer , you could post your answer I was curious how you did

  • I edited my question to be more complete, and there I put as I did. Check there and tell me what you think.

  • @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

  • 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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.