1

I'd like two merge two array with a custom order: take one value from array one and then one from array two as following:

$array1 = array('key1' => 'value_1_1', 'key2' => 'value_1_2');
$array2 = array('key1' => 'value_2_1', 'key2' => 'value_2_2');

//merge array with custom order

$array_result = array('key1' => array('value_1_1', 'value_2_1'),
                      'key2' => array('value_2_1', 'value_2_2')
                     )

Values are different, keys same on both arrays.

5
  • You'd have to rename the keys because you can't have duplicate key values. Commented Feb 6, 2014 at 3:09
  • The solution could be create multi dim arrays, but the key has to be the same Commented Feb 6, 2014 at 3:11
  • This should be the same question as stackoverflow.com/questions/21512889/… Commented Feb 6, 2014 at 3:14
  • No, keys are actually strings not int Commented Feb 6, 2014 at 3:16
  • What shall happen to keys only present in one array? Commented Feb 6, 2014 at 3:42

3 Answers 3

2

Built-in function

$result = array_merge_recursive($array1, $array2);
0
$result = array();
foreach(array_keys($array1 + $array2) as $key)
{
    if(array_key_exists($key, $array1) && array_key_exists($key, $array2))
        $result[$key] = array($array1[$key], $array2[$key]);
    else
        $result[$key] = array_key_exists($key, $array1) ? $array1[$key] : $array2[$key];
}
-1

Try this :

$array1 = array('key1' => 'value_1_1', 'key2' => 'value_1_2');
$array2 = array('key1' => 'value_2_1', 'key2' => 'value_2_2');
$result = array();

/* Create index for $result */
foreach($array1 as $data => $value) {
    $result[$data] = array();
}

/* Craete Value for $result from array 1*/
foreach($array1 as $data => $value) {
    array_push($result[$data], $value); 
}

/* Craete Value for $result from array 2*/
foreach($array2 as $data => $value) {
    array_push($result[$data], $value);
}

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.