0

I've got two keyed arrays, say

$a = [ 'Arvind' => 'Basu', 'Rampal' => 'Singh' ];

and

$b = [ 'Anjali' => 'Basu', 'Roopashri' => 'Singh' ];

which I need to merge together in the format

$c = [ 'Arvind' => 'Basu', 'Anjali' => 'Basu' ,'Rampal' => 'Singh', 'Roopashri' => 'Singh' ];

(basically append the two arrays together and sorted according to surnames).

I've tried using the array_merge function to merge the two arrays, however, that dosen't seem to work.

Sohom Datta
  • 30
  • 1
  • 5

2 Answers2

0

This should do. Here's a sample.

$a = [ 'Arvind' => 'Basu', 'Rampal' => 'Singh' ];
$b = [ 'Anjali' => 'Basu', 'Roopashri' => 'Singh' ];

$c = array_merge($a, $b);
ksort($c);
echo print_r($c);
Vladan
  • 1,572
  • 10
  • 23
0

Your sorting appears to be a bit more complicated than it first appears. You want to sort first by value and then by key. You can use array_multisort for this.

<?php
$a = [ 'Arvind' => 'Basu', 'Rampal' => 'Singh' ];

$b = [ 'Anjali' => 'Basu', 'Roopashri' => 'Singh' ];

// You could also use `array_merge`. You should read about the differences.
// https://stackoverflow.com/a/7059731/296555
$c = $b + $a;

array_multisort(array_values($c), SORT_ASC, array_keys($c), SORT_ASC, $c);

var_dump($c);

array(4) {
  ["Anjali"]=> string(4) "Basu"
  ["Arvind"]=> string(4) "Basu"
  ["Rampal"]=> string(5) "Singh"
  ["Roopashri"]=> string(5) "Singh"
}
waterloomatt
  • 3,662
  • 1
  • 19
  • 25