Search code examples
phparraysmultidimensional-arraytranspose

Transpose the data from multiple flat arrays to create an indexed array with associative rows


I have a form that is posting 4 arrays that I need to combine and eventually compose to email. The four arrays:

$quantityArray    = $this->input->post('qty');
$dimensionArray   = $this->input->post('dimension');
$thicknessArray   = $this->input->post('thickness');
$descriptionArray = $this->input->post('description');

will all have the same array length and each index will be related. How do I combine the 4 arrays such as

[0]
     'qty' => '1',
     'dimenesion => '2x2',
     'thickness' => '2in',
     'description' => 'this is the description'
[1]
     'qty' => '1',
     'dimenesion => '2x2',
     'thickness' => '2in',
     'description' => 'this is the description'

I have tried array_combine(), array_merge() and can't get the results that I am looking for.


Solution

  • If you have same length for those arrays here is example code:

    $resultArray = array();
    foreach($quantityArray as $index => $qty) {
        $resultArray[$index]['qty'] = $qty;
        $resultArray[$index]['dimenesion'] = $dimensionArray[$index];
        $resultArray[$index]['thickness'] = $thicknessArray[$index];
        $resultArray[$index]['description'] = $descriptionArray [$index];
    }
    
    print_r($resultArray);