0

For example i have two arrays like:

$first_array = array(
    1 => 'a',
    2 => 'b',
    3 => 'c',
    4 => 'd',
    5 => 'e'
);

$second_array = array(
    1 => 'not important',
    4 => 'not important',
    3 => 'not important',
    5 => 'not important',
    2 => 'not important',
);

Is there any function that could arrange first array keys (with values) in sequence of second array keys? Or i just need to loop second array and recreate first by keys?

Update: Result values should be arranged by seconds arrays keys sequence

$result = array(
    1 => 'a',
    2 => 'd',
    3 => 'c',
    4 => 'e',
    5 => 'b'
);
Kin
  • 4,466
  • 13
  • 54
  • 106

3 Answers3

0

same question is already posted

Sort array by keys of another array

Sort an Array by keys based on another Array?

Hope will help!

Community
  • 1
  • 1
Rajiv Ranjan
  • 1,869
  • 1
  • 11
  • 20
0

You can do something like this...

<?php
$first_array = array(
    1 => 'a',
    2 => 'b',
    3 => 'c',
    4 => 'd',
    5 => 'e'
);

$second_array = array(
    1 => 'not important',
    4 => 'not important',
    3 => 'not important',
    5 => 'not important',
    2 => 'not important',
);


foreach($first_array as $k=>$v)
{
$second_array[$k]=$v;
}

$result = array_values($second_array);
array_unshift($result, "dummy");
unset($result[0]);
print_r($result);

OUTPUT:

Array
(
    [1] => a
    [2] => d
    [3] => c
    [4] => e
    [5] => b
)
Shankar Narayana Damodaran
  • 68,075
  • 43
  • 96
  • 126
0

you can do it by using single foreach() loop and array_flip(); and array_combine();

     $f = array(
    1 => 'a',
    2 => 'b',
    3 => 'c',
    4 => 'd',
    5 => 'e'
);
$s = array(
    1 => 'dummy',
    4 => 'dummy',
    3 => 'dummy',
    5 => 'dummy',
    2 => 'dummy',
);
$c=array();
$j=1;
foreach($s as $k=>$v){

$c[]=$f[$k];

}
$f=array_flip($f);
$c=array_combine($f,$c);

print_r($c);
Nambi
  • 11,944
  • 3
  • 37
  • 49