php merge 2 arrays into one associative array
Asked Answered
B

3

2

Using PHP I need to merge 2 arrays (of equal length into one associative array) here is an excerpt from my current data set:

[1] => Array
    (
        [0] => C28
        [1] => C29
    )

[2] => Array
    (
        [0] => 1AB010050093
        [1] => 1AB008140029
    )

both elements [1] and [2] are actually a lot longer than just 2 sub-elements (like I said, this is an excerpt).

The deal is that "C28" in the first array corresponds to "1AB010050093" in the second array, and so on... The result I need is to create a new associative array that looks like this:

[1] => Array    
    (
        ['ref']  => C28
        ['part'] => 1AB010050093
    )
[2] => Array
    (
        ['ref'] => C29
        ['part'] => 1AB008140029
    )

and so on...

Bullard answered 23/6, 2013 at 1:30 Comment(2)
Do you need to combine them into one multi-dimensional array, or do you want the result to be 2 separate single-dimensional arrays?Selfhood
What have your tried? This can be done in about 4 lines of code.Lophophore
H
4

If you are willing to compromise with an array structure like this:

array(
    'C28' => '1AB010050093',
    'C29' => '1AB008140029'
);

Then you can use the array_combine() (Codepad Demo):

array_combine($refNumbers, $partIds);

Otherwise, you'll need to use a foreach (Codepad Demo):

$combined = array();

foreach($refNumbers as $index => $refNumber) {
    if(!array_key_exists($index, $partIds)) {
        throw OutOfBoundsException();
    }

    $combined[] = array(
        'ref'  => $refNumber,
        'part' => $partIds[$index]
    );
}
Harrumph answered 23/6, 2013 at 1:39 Comment(2)
I think I can probably use the first array structure and just use combine, thanksBullard
@Bullard Although it likely won't matter in the long run, array_combine() will be slightly faster too since its an internal.Harrumph
S
0

If you're using PHP 5.5+, there is a new method called array_column(), which will get all of the values in a particular column. That could potentially be used, although I think just a simple foreach loop will probably still be your best bet.

Selfhood answered 23/6, 2013 at 1:49 Comment(0)
G
0

How about:

$arr1 = array(
    0 => 'C28',
    1 => 'C29',
);

$arr2 = array(
    0 => '1AB010050093',
    1 => '1AB008140029',
);
$result = array();
for ($i=0; $i<count($arr1); $i++) {
    $result[] = array('ref' => $arr1[$i], 'part' => $arr2[$i]);
}
print_r($result);

ouptut:

[1] => Array
    (
        [0] => C28
        [1] => C29
    )

[2] => Array
    (
        [0] => 1AB010050093
        [1] => 1AB008140029
    )
Guenon answered 23/6, 2013 at 9:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.