$vacancies = 13;
$list_order_id = [ 1, 5, 6, 9, 10 ];
$arrayOrder = [];
$last_id = 6;
for ( $i = 0; $i < $vacancies; $i )
{
// last_id = 6
// next id = 9 ( starter )
// result => $arrayOrder = [ 9, 10, 1, 5, 6, 9, 10, 1, 5, 6, 9, 10, 1 ];
anyone help me find this result?
}
I need make array result from the initial value by number of vacancies
thanks
CodePudding user response:
$vacancies = 13;
$list_order_id = [ 1, 5, 6, 9, 10 ];
$last_id = 6;
// Count of ids
$count = count($list_order_id);
// How many times does the list of ids need to be repeated so that there are enough items
$times = intdiv($vacancies, $count) 2;
// Repeat the list of ids that many times
$list = array_merge(... array_fill(0, $times, $list_order_id));
// Index of the first occurrence of the element the list should start with
$start = array_search($last_id, $list) 1;
// Extract the slice starting at that index with the desired length
$result = array_slice($list, $start, $vacancies);
print_r($result);
Output:
Array
(
[0] => 9
[1] => 10
[2] => 1
[3] => 5
[4] => 6
[5] => 9
[6] => 10
[7] => 1
[8] => 5
[9] => 6
[10] => 9
[11] => 10
[12] => 1
)
CodePudding user response:
You have supplied the lookup array, the number of iterations, and the value before the starting value.
The only things left to do are:
- Find the count of the lookup,
- Find the index of the last value in the lookup,
- Loop the expressed number of times,
- Use a modulus calculation to find the next appropriate value in the lookup, and
- Push values into the result array.
This can be done with no iterated function calls.
Code: (Demo)
$count = count($list_order_id);
$index = array_search($last_id, $list_order_id);
$result = [];
for ($i = 0; $i < $vacancies; $i) {
$result[] = $list_order_id[ $index % $count];
}
var_export($result);