Home > Back-end >  Populate array by recycling a smaller array starting with a particular value
Populate array by recycling a smaller array starting with a particular value

Time:07-07

I need to populate an array with a predefined number of elements ($vacancies) using a pre-existing array of values ($list_order_id).

The source array may not contain enough values to meet the required number of elements in the result array so the source array should be recycled as needed.

Also, the starting value in the result array must start with the value that immediately follows a predefined value ($last_id).

$vacancies = 13;
$list_order_id = [1, 5, 6, 9, 10];
$last_id = 6; // next id = 9 ( starter )

$arrayOrder = [];
for ($i = 0; $i < $vacancies; $i  ) {
    // what goes here?
}

Expected result:

[9, 10, 1, 5, 6, 9, 10, 1, 5, 6, 9, 10, 1]

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:

  1. Find the count of the lookup,
  2. Find the index of the last value in the lookup,
  3. Loop the expressed number of times,
  4. Use a modulus calculation to find the next appropriate value in the lookup, and
  5. 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);
  • Related