Skip to content
Advertisement

I have two array in php. Need to combing in one at following way [closed]

I have two arrays:

$array1 = array('104', '104', '104', '51', '228', '228');

$array2 = array('12121', '12120', '12119', '11821', '11788', '11787');

I need to create an array with two dimensions consisting of the elements of these two arrays in a specific way:

$array3 = array('104'=>array('12121', '12120', '12119'),'51'=>array('11821'),'228'=>array('11788', '11787'));

Array1 and Array2 always have the same number of elements. How can I do this?

Advertisement

Answer

You can do it this way:

<?php
$array1 = ['104', '104', '104', '51', '228', '228'];
$array2 = ['12121', '12120', '12119', '11821', '11788', '11787'];
$result = [];

$index = 0;
foreach( $array1 as $key => $value ){
    $result[$value][] = $array2[$index];
    $index++;
}

Result:

enter image description here

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement