Assume a master array which is already sorted in ASCENDING order:
$values = array('value1', 'value2', 'value3', 'value4', 'value5', 'value6');
And another array with the keys(indexes) being ordered per some specific requirement.
$keys = array(0, 2, 1, 5);
Required Logic: should create an array say $output
- beginning with elements of
$valueswho’s indexes are stored$keyspreserving the order of indexes. - remaining elements of
$valuesshall be appended in the rear in ascending order.
e.g. 1
$values = array('value1', 'value2', 'value3', 'value4', 'value5', 'value6');
$keys = array(0, 2, 1, 5);
$output = array('value1', 'value3', 'value2', 'value6', 'value4', 'value5');
e.g. 2
$values = array('value1', 'value2', 'value3', 'value4', 'value5', 'value6');
$keys = array(5);
$output = array('value6', 'value1', 'value2', 'value3', 'value4', 'value5');
e.g. 3
$values = array('value1', 'value2', 'value3', 'value4', 'value5', 'value6');
$keys is empty, no keys(indexes).
$output = array('value1', 'value2', 'value3', 'value4', 'value5', 'value6');
I’ve $values and $keys arrays. I just need to figure out how to create $output array. I’m pretty sure there will need to be a foreach loop on the $values array for this to work.
I’m running into a wall here trying to figure this thing out…
Try this…
Basically parsing the
$valuesarray and pulling the relevant value out.Unsetting the array as we go to leave only the values which were not sorted.
The remaining items in the array will be merged after the loop. with array_merge.
Unsetting the array doesn’t change the index values, which is useful in this situation.
There will be errors if there are more
$keysthan$valuesthough. Need to add some error checks.