Search code examples
phparraysmultidimensional-arraymappingassociative-array

Map associative element of a multidimensional array to form a flat associative array


I am having no success using array_combine(). Can anyone help me to produce a flat associative array from the data in my two rows?

array
  0 => 
    array
      0 => 
        array
          'traitvalue01' => string 'width'
          'traitvalue02' => string 'Length'
          'traitvalue03' => string 'Top'
          'traitvalue04' => string 'Bottom'
  1 => 
    array
      0 => 
        array
          'trait01' => string '7 in'
          'trait02' => string '25 in'
          'trait03' => string '3 in'
          'trait04' => string '3 in'

Expected result:

array (
    'width'  => '7 in',
    'Length' => '25 in',
    'Top'    => '3 in',
    'Bottom' => '3 in',
)

Solution

  • Here is my solution:

    <?php
    
    $a = array(
            array(
                array(
                    'traitvalue01' => 'width',
                    'traitvalue02' => 'Length',
                    'traitvalue03' => 'Top',
                    'traitvalue04' => 'Bottom'
                )
            ),
            array(
                array(
                  'trait01' => '7 in',
                  'trait02' => '25 in',
                  'trait03' => '3 in',
                  'trait04' => '3 in'
                )
            )
        );
    
    print_r(array_combine($a[0][0], $a[1][0]));
    
    ?>
    

    And this is the output:

    Array
    (
        [width] => 7 in
        [Length] => 25 in
        [Top] => 3 in
        [Bottom] => 3 in
    )