Perocat
Perocat

Reputation: 1521

PHP array_merge order one value per array

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.

Upvotes: 1

Views: 447

Answers (3)

clouddreams
clouddreams

Reputation: 642

Built-in function

$result = array_merge_recursive($array1, $array2);

Upvotes: 2

Zoom
Zoom

Reputation: 21

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);
}

Upvotes: -1

wonce
wonce

Reputation: 1921

$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];
}

Upvotes: 0

Related Questions