array_merge inside a foreach

6

I am trying to join two arrays , I have the following:

In the variable $ventas I have the following object:

{
  "Mesa": [
    {
      "producto": "Mesa",
      "mes": "6",
      "total": "1"
    },
    {
      "producto_id": "0",
      "mes": "7",
      "total": "198"
    }
  ],
  "Silla": [
    {
      "producto_id": "Silla",
      "mes": "7",
      "total": "1"
    }
  ]
}

I also have another% co_of% of months:

$months = [
        '1' => 0, 
        '2' => 0, 
        '3' => 0, 
        '4' => 0,
        '5' => 0,
        '6' => 0,
        '7' => 0,
        '8' => 0,
        '9' => 0,
        '10' => 0, 
        '11' => 0,
        '12' => 0
    ];

I performed operations with array

foreach ($ventas as $indeOne => $venta) {
            foreach ($venta as $indexTwo => $value) {
                $array_1[$indeOne] = $value;
                foreach ($months as $indexTree => $month) {
                    if($indexTree == $value->mes){
                        $new[$indeOne][$indexTree] = $value->total;

                    }
                }
            }
        }

And this brings back the following:

{
  "Mesa": {
    "6": "1",
    "7": "198"
  },
  "Silla": {
    "7": "1"
  }
}

What tells me that in month 6 has 1 sale and in month 198 so on.

But the result that I try to obtain is the following:

{
  "Mesa": [
    {
      "1": 0,
      "2": 0,
      "3": 0,
      "4": 0,
      "5": 0,
      "6": 1,
      "7": 198,
      "8": 0,
      "9": 0,
      "10": 0,
      "11": 0,
      "12": 0,
    },
  ],
  "Silla": [
    {
      "1": 0,
      "2": 0,
      "3": 0,
      "4": 0,
      "5": 0,
      "6": 1,
      "7": 1,
      "8": 0,
      "9": 0,
      "10": 0,
      "11": 0,
      "12": 0,
    },
  ]
}}

I tried to put a foreach into the foreach, but it unites me badly.

    
asked by Carlos Mendez 10.08.2018 в 22:53
source

2 answers

1

You just have to change the order of your foreach and add a elseif . Something like this:

foreach ($ventas as $indeOne => $venta) {
    foreach ($months as $indexTree => $month) {
        foreach ($venta as $indexTwo => $value) {
            if($indexTree == $value->mes){
                $new[$indeOne][$indexTree] = $value->total;
            } elseif(!isset($new[$indeOne][$indexTree])) {
                $new[$indeOne][$indexTree] = 0;
            }
        }
    }
}
    
answered by 10.08.2018 / 23:08
source
1

I think it's best to put the array of months whole and only modify by index:

foreach ($ventas as $indeOne => $venta) {
        //Guardar llave con los meses
        $array_1[$indeOne][0] = $months;

        foreach ($venta as $indexTwo => $value) {
            //Llenar informacion de meses
             $array_1[$indeOne][0][$value['mes']] = $value['total']; 
        }
    }
    
answered by 10.08.2018 в 23:26