I have an dynamic array that could for example look like this:
$arr = array(42, 30, 70, 10);
I have a function called CreateOrder
and I want it to return an array like this
function createOrder($array)
{
/*
This function should return an array starting at 0,
while keeping the correct order, like this:
*/
$new_array = array(2, 1, 3, 0);
}
I have been trying and trying with foreach loops but I can't get my head around it.
Any help appreciated,
Nathan
If you don't mind the order of the original array being trashed in the process:
asort($arr);
$new_array = array_combine(array_keys($arr), range(0,count($arr)-1));
ksort($new_array);
Not so bad inside a function, because that uses a copy of the original array unless you pass by reference, so only the order of the locally-function-scoped copy gets trashed
Or even more simply:
asort($arr);
$new_array = array_keys($arr);
asort($new_array);
$newArr = array_keys($new_array);
Maybe the asort() function will fit your needs: http://php.net/manual/de/function.asort.php
Don't forget to pass your array by reference, so this has to be called as is (without an assignment).
Following code will help
function createOrder($array){
$cloneArray = asort($array);
$positionArray = [];
foreach($cloneArray as $element){
$positionArray[] = array_search($element,$array);
}
return $positionArray;
}