0

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;

}

1
  • Values with unique key has extra comma. Is it important? Commented Jan 17, 2014 at 0:44

1 Answer 1

2

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.