0

I have two arrays in PHP:

Array1
(
    [0] => 1
    [1] => 2
    [2] => 2
)
Array2
(
    [0] => 18
    [1] => 19
    [2] => 20
)

Array1 contains the Ids of Delivery Addresses. Array2 contains the Ids of Contacts.

Array1 and Array2 are 'aligned' so that Contact 18 (Array2[0]) resides at Delivery Address Id #1 (Array1[0]) (and so on).

What I would like is use the unique values of Array1 as array keys for Array3, and the values of Array2 used as the array values Array3.

The end result being that Contacts are 'grouped' by their Delivery Address.

Like so:

Array 3
(
   [1] = array (
                 [0] => 18
               )
   [2] = array (
                 [0] => 19
                 [1] => 20
               )
)
2
  • Kudos to @hsz for providing a good solution so quickly, but I feel like mentioning this sounds like terrible design. Commented May 20, 2011 at 14:26
  • Agreed - it's not ideal, but is designed to work within a very specific scenario (AJAX request sending POST). That said, if you have any suggestions, please let me know :) Commented May 20, 2011 at 14:30

2 Answers 2

10
$array3 = array();
foreach ( $array1 as $k => $v ) {
    if ( !isset($array3[$v]) )
        $array3[$v] = array();

    $array3[$v][] = $array2[$k];
}

var_dump($array3);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks hsz. This results in exactly what I was asking for. And kudos for the speed of answering (<2mins) :)
0

Synchronously iterate the two arrays by traversing one array with a foreach() and access the corresponding value using the shared index. When pushing array elements using square brace syntax it is unnecessary to declare the parent as an empty array. Demo

$array1 = [1, 2, 2];
$array2 = [18, 19, 20];

$result = [];
foreach ($array1 as $i => $id) {
    $result[$id][] = $array2[$i];
}
var_export($result);

Output:

array (
  1 => 
  array (
    0 => 18,
  ),
  2 => 
  array (
    0 => 19,
    1 => 20,
  ),
)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.