views:

133

answers:

6

How can you combine the two arrays?

They are simplified as follows which is enough for this question. This question is based on this answer.

1

[a][b][]

and

2

[a][c]

where both arrays has one common subarray [a].

I would like to have this

[a][c][b][]

I have run the following command unsuccessfully

array1[a] + array2[a]
A: 

$array1 = array_merge($array1, $array2);

Lucky
This leaves out the column $b which I do not want, since they are the titles of questions.
Masi
A: 

PHP provides you a solution to solve this common problem:

$a = array_merge($b, $c);

With this solution you're going to take all the elements inside $b and merge them with $c. But if you're using associative arrays, you should notice you're going to replace the values in $b with the ones in $c.

For example:

<?php

$a = array(
    'ka' => 1,
    'kb' => 1,
);

$b = array(
    'kb' => 2,
    'kc' => 2,
);

print_r(array_merge($a, $b));


?>

The result of this code will be something like:

Array
(
    [ka] => 1
    [kb] => 2
    [kc] => 2
)
Pablo López Torres
This does not work. It leaves out the titles. - **How can you determine the column which the function merges?**
Masi
A: 
for($i = 0; $i < sizeof($array); $i++)
{
     $mergedarray[a][b] = $a[a][b];
     $mergedarray[a][c] = $b[a][c];
}

as far as i can tell this is what you want, that way both the sub-keys have the same root key.

Adrian Guido
A: 

try array_combine()

http://us2.php.net/manual/en/function.array-combine.php

william
+1  A: 
foreach($array1 as $a => $c)
{
    $end_array[$c] = $array2[$a];
}


or

// For every [a]
foreach($array1 as $a => $c)
{
    // Get the [b]
    $b = $array2[$a];

    // Add it to [a][c]
    $end_array[$a][$c] = $b;

    // Making it $end_array[$a][$c][$b] = array(....);
}
Chacha102
+1  A: 

Ok, I see what you're talking about. (For everyone else, see the link he posted: http://dpaste.com/81464/)

var $output = array();

foreach ($array1 as $index => $a1) {
    $output[$index] = $a1;
    $output[$index]['title'] = $array2[$index]['title'];
}
nickf