I'd do:
<?php
$newarray = array_fill_keys($indices, $values);
?>
This assumes your indices are always unique of course.
سؤال
I have the following two hypothetical arrays:
$values = array("fourth", "first", "second", "third");
$indices = array(3, 0, 1, 2);
What is the fastest way to rearrange $values
based on $indices
?
Is there perhaps some way to do $values->index_array = $indices
?
المحلول 2
I'd do:
<?php
$newarray = array_fill_keys($indices, $values);
?>
This assumes your indices are always unique of course.
نصائح أخرى
It's just a guess based on a phrase from the question:
way to rearrange $values based on $indices
$values = array("fourth", "first", "second", "third"); $indices = array(3, 0, 1, 2);
array_multisort($indices, $values);
var_dump($values);
Online demo: http://ideone.com/UKfNiq
Output is:
array(4) {
[0]=>
string(5) "first"
[1]=>
string(6) "second"
[2]=>
string(5) "third"
[3]=>
string(6) "fourth"
}
ZerkMS's answer is correct as defined by the question but you may be better off taking another approach to generating the results.
If you can, rather than generating two arrays of:
$values = array("fourth", "first", "second", "third");
$indices = array(3, 0, 1, 2);
instead just generate one array and call ksort on it:
$valuesToSort = array();
$valuesToSort[3] = 'fourth';
$valuesToSort[0] = 'first';
$valuesToSort[1] = 'second';
$valuesToSort[2] = 'third';
ksort($valuesToSort);