php – array_merge into a foreach

Question:

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 array 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 foreach

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 returns the following to me:

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

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

But the result I'm trying to get 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 an array_merge() inside the foreach, but it binds me wrong.

Answer:

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

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;
            }
        }
    }
}
Scroll to Top