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'
);
10
  • 4
    ? I don't get it? What is the expected output? Commented Dec 4, 2013 at 11:50
  • No, you have to use loop for that. Commented Dec 4, 2013 at 11:50
  • contrary to popular belief php doesn't have a function/method for everything. Commented Dec 4, 2013 at 11:51
  • what would be the function header? Commented Dec 4, 2013 at 11:54
  • 2
    @gwillie just don't want to reinvent the bicycle Commented Dec 4, 2013 at 11:55

3 Answers 3

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!

Sign up to request clarification or add additional context in comments.

Comments

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
)

Comments

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);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.