php merge 2 arrays into one associative array

2019-07-19 06:44发布

问题:

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...

回答1:

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


回答2:

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.



回答3:

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
    )