How can I avoid duplicate data when filling an array from an sql query?

1

I want to bring several data according to the year to which the data belongs, but when making a foreach I create more arrangements with the same year, and does not unify the data for the same year:

See base de datos :

   $dataa = DB::table('vista_matriculas_todas')
                 ->select(DB::raw('vista_matriculas_todas.ano_inf as anio,meses.id AS MES,SUM(cantidad) as MAT'))
                 ->join('meses', 'meses.id', '=', 'vista_matriculas_todas.mes_corte')
                 ->whereIn('vista_matriculas_todas.ano_inf',explode(",", $anio))
                 ->whereIn('vista_matriculas_todas.sector',explode(",", $sector))
                 ->whereIn('vista_matriculas_todas.calendario',explode(",", $calendario))
                 ->groupBy('vista_matriculas_todas.ano_inf')
                 ->groupBy('meses.id')
                 ->orderBy('vista_matriculas_todas.ano_inf','DESC')
                 ->orderBy('meses.id','ASC')
                 ->get();

This is what it brings from the base de datos :

You are in the php function:

for ($i=0; $i <=11; $i++) 
{
  $matriculas[$i]=0;
}

foreach ($dataa as $data)
{
  $diasel = intval($data->mes);
  $matriculas[$data->mes-1]=$data->mat;
  $mes = array('anioTtile'=>$data->anio,'anioData'=>$matriculas);
  $datos[] = $mes;
}
return json_encode($datos);

This is the result in consola :

0:{anioTtile: 2018, anioData: ["13", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]}
1:{anioTtile: 2017, anioData: ["174725", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]}
2:{anioTtile: 2017, anioData: ["174725", "10344", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]}

So what I really want to see is:

0:{anioTtile: 2018, anioData: ["13", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]}
1:{anioTtile: 2017, anioData: ["174725", "10344", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]}
    
asked by Andrés Cantillo 07.06.2018 в 22:54
source

1 answer

0

You can group it for years and fill an array of months, like the example below:

for ($i=0; $i <=11; $i++) {
              $matriculas[$i]=0;
    }
    $datos= [];
    foreach ($dataa as $data)  {
        if (!$datos["-".$data->anio]){
           $datos["-".$data->anio] = array("anioTtile" =>$data->anio ,"anioData"  => $matriculas);

         }
         $datos["-".$data->anio]["anioData"][$data->mes-1] = $data->mat;

    }
    return   json_encode($datos);
    
answered by 08.06.2018 в 00:49