-6

I have 2 arrays and need to sort $array1 based on the keys of $array2. Here are the arrays:

$array1 = array(
  'a1' => 'text1', 
  'a2' => 'text2', 
  'a3' => 'text3', 
  'a4' => 'text4'        
);

$array2 = array(
  'a2' => '1',       
  'a1' => '1', 
  'a3' => '0', 
  'a4' => '0'
);

After sorting, $array1 should look like this.

$array1 =  array(
      'a2' => 'text2',           
      'a1' => 'text1', 
      'a3' => 'text3', 
      'a4' => 'text4'          
    );

I do not want to duplicate the array, but want $array1 to be mutated. In addition, sometimes $array2 will not contain all the keys in $array1.

Drenmi
  • 8,492
  • 4
  • 42
  • 51
user3351236
  • 2,488
  • 10
  • 29
  • 52
  • 3
    What you have tried so far? It is not a question – Ayaz Ali Shah Jul 12 '17 at 08:45
  • Your problems makes no sense. Why would you sort one array by keys of another? – Difster Jul 12 '17 at 08:45
  • 4
    Possible duplicate of [Sort an Array by keys based on another Array?](https://stackoverflow.com/questions/348410/sort-an-array-by-keys-based-on-another-array) Oddly enough the name of that topic is the same. Did you search for it? – Andreas Jul 12 '17 at 08:46

1 Answers1

1

You can foreach it with key.

$array1 = array(
  'a1' => 'text1', 
  'a2' => 'text2', 
  'a3' => 'text3', 
  'a4' => 'text4'        
);

$array2 = array(
  'a2' => '1',       
  'a1' => '1', 
  'a3' => '0', 
  'a4' => '0'
);

foreach($array2 as $key => $value){
    if(isset($array1[$key])) echo $array1[$key]."\n";
}

https://3v4l.org/65MrV

Andreas
  • 23,610
  • 6
  • 30
  • 62