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: