phparraysmultidimensional-arraymappingmerging-data

Merge multiple arrays into one 2d array with associative rows


This is what I'm trying to arrive at:

array (
  'category_0' => 
  array (
    'count' => 12,
    'avg' => 11,
  ),
  'category_1' => 
  array (
    'count' => 14,
    'avg' => 13,
  ),
  'category_2' => 
  array (
    'count' => 16,
    'avg' => 15,
  ),
  'category_3' => 
  array (
    'count' => 18,
    'avg' => 17,
  ),
)

From the following:

$category = 
array (
  0 => '9',
  1 => '10',
  2 => '11',
  3 => '12',
)

and:

$count =
array (
  0 => '12',
  1 => '14',
  2 => '16',
  3 => '18',
)

and:

$avg = 
array (
  0 => '11',
  1 => '13',
  2 => '15',
  3 => '17',
)

I've arrived at the $count and $avg variables by performing some other methods using a foreach on the $category and the array_map function. Now I need to rejoin everything per the intial example. I've tried array_merge() but am unable to get it to work correctly. The key name of 'category_x' is unimportant. I'm not even sure if it's possible to get the final result in the order I need it. Any help would be appreciated.


Solution

  • Using a combination of array_keys and a foreach loop, you can easily accomplish this.

    Example:

    <?php
    
    $category = array (
        0 => '9',
        1 => '10',
        2 => '11',
        3 => '12'
    );
    $count = array (
        0 => '12',
        1 => '14',
        2 => '16',
        3 => '18'
    );
    $avg = array (
        0 => '11',
        1 => '13',
        2 => '15',
        3 => '17'
    );
    
    $out = array();
    $key = array_keys($category);
    foreach ($key as $key) {
        $out["category_{$key}"] = array(
            'count' => isset($count[$key]) ? $count[$key] : 0,
            'avg' => isset($avg[$key]) ? $avg[$key] : 0
        );
    }
    print_r($out);
    

    Output:

    Array
    (
        [category_0] => Array
            (
                [count] => 12
                [avg] => 11
            )
    
        [category_1] => Array
            (
                [count] => 14
                [avg] => 13
            )
    
        [category_2] => Array
            (
                [count] => 16
                [avg] => 15
            )
    
        [category_3] => Array
            (
                [count] => 18
                [avg] => 17
            )
    
    )