Search code examples
phparrayslaravelmultidimensional-arraytranspose

How to add multiple array elements into a transposed structure?


I have these arrays

$months = ['jan', 'feb'];

$cashUniform = [2000, 1200];

$cashFee = [24000, 34000];

$cashExpenses = [4000, 300];

Am trying to create an object from these arrays like so:

$data = [{
 'month': 'jan',
 'cashUniform': 2000,
 'cashFee': 24000,
 'cashExpenses': 4000,
},
{
 'month': 'feb',
 'cashUniform': 12000,
 'cashFee': 34000,
 'cashExpenses': 300,
 }
];
    

I've tried array_combine but it only accepts two array elements, and in my case, I have four array elements.

I've also tried to to create a multiple array.

  $data['months'] = $months;
  $data['cashFee'] = $cashFee;
  $data['cashUniform'] = $cashUniform;
  $data['cashExpenses'] = $cashExpenses;
  dd(json_encode($data));

The code above returns

{"months":["JAN","FEB"],"cashFee":   [12500,2000],"cashUniform":[2000,0],"cashExpenses":[1500,0]}

Solution

  • You can use a simple for loop to loop over all arrays and add the values to a single array:

    $data = [];
    for ($i = 0; $i < count($months); $i++) {
        $data[] = [
            'month' => $monts[$i],
            'cashUniform' => $cashUniform[$i],
            'cashFee' => $cashFee[$i],
            'cashExpenses' => $cashExpenses[$i],
        ];
    }
    
    dd($data);
    

    This does require that all arrays have the same amount of values!