I have two arrays, one has string elements and the other one has exactly the position where those elements are supposed to be. In the second array key represents a position and the value represents where the value from the first array is supposed to be. But I cant not manage make it work. This is the code that I have so far:
<?php
$array1= array("d","c","b","e","a");
$poss = array (3 ,2 ,1 ,4 ,0);
var_dump(orderArray($poss, $array1));
function orderArray($poss, $data){
$countPoss = count($poss);
$countData = count($data);
if ($countPoss === $countData){
for ($i=0; $i<$countData; $i++){
if($poss[$i]!==$i){
$aux = $data[$i];
$data = insertArrayIndex($data, $aux, $poss[$i]);
unset($data[$i]);
$data = array_values($data);
}
}
}else{
return FALSE;
}
return $data;
}
function insertArrayIndex($array, $new_element, $index) {
$start = array_slice($array, 0, $index);
$end = array_slice($array, $index);
$start[] = $new_element;
return array_merge($start, $end);
}
In other words, $array1 is supposed to be organized according to $poss. E.g.: the first element in $array1 'd' is supposed in in position 3 at the end, and 'a' is supposed to be in position 0.
I've been trying hundreds of things, but I can not figure it out.
$new_array = array_combine($poss, $array1); asort($new_array);