Mark Kennedy
Mark Kennedy

Reputation: 1781

PHP - merge multi-dimensional array based on keys

Suppose I have a multi-dimensional array:

Array
(
    [0] => Array
        (
            [7,14] => 0.0,3.0
            [5,11] => 0.0,5.0
            [8,6] => 0.0,6.0
        )

    [1] => Array
        (
            [7,14] => 0.0,1.0
            [5,11] => 1.0,3.0
            [11,13] => 1.0,1.0
            [6,8] => 1.0,0.0

        )

I want to form a new array with keys as the union of all keys in each array and the values as the corresponding values of those unioned keys. If a key is ONLY found in one sub-array, then fill the would-be data with commas

i.e result ----------

Array
(
             [7,14] => 0.0,3.0,0.0,1.0             // <--- union 0.0,3.0 and 0.0,1.0
             [5,11] => 0.0,5.0,1.0,3.0
             [8,6] => 0.0,6.0,,
             [11,3] => 1,0,1.0,,
             [6,8] => 1.0,0.0,,

)

Here's what I've tried. I'm pretty close to the right answer!

function combineValues($bigArray){

$combinedArray = array();

   for($i = 0; $i < (count($bigArray) - 1); $i++) {


      $keys = array_keys($bigArray[$i]);

      for($j = 0; $j < count($keys); $j++){

            $currentKey = $keys[$j];

        if (isset($bigArray[$i+1][$currentKey]){
            $combinedArray[$currentKey] = $bigArray[$i][$currentKey] + "," + $bigArray[$i+1][$currentKey];
        } else {

        }


    }

  }

  return $combinedArray;

}

Upvotes: 0

Views: 173

Answers (1)

sectus
sectus

Reputation: 15454

It is easy to use foreach instead of for.

$array2 = [[1, 2, 3, 4], [2 => 7, 8, 9]];
$return_array = array();    
foreach ($array2 as $array1)
    {
    foreach ($array1 as $key => $value)
        {
        if (isset($return_array[$key]))
            $return_array[$key].=',' . $value;
        else
            $return_array[$key] = $value;
        }
    }

var_dump($return_array);

Also you could use functional features of language. array_walk_recursive

$array2 = [[1, 2, 3, 4], [2 => 7, 8, 9]];

$return_array = array();

array_walk_recursive($array2, function ($value, $key)use(&$return_array)
        {
        if (isset($return_array[$key]))
            $return_array[$key].=',' . $value;
        else
            $return_array[$key] = $value;
        });

var_dump($return_array);

Upvotes: 2

Related Questions