Home > Back-end >  Split ascending integers when non-consecutive and assign sequences to values in another array
Split ascending integers when non-consecutive and assign sequences to values in another array

Time:11-02

I have 2 flat arrays which are Leaders and Members. These arrays are populated while incrementing ids.

I would like to associate one leader id with a sequence of consecutive ids in the members array. If there are too many leaders and not enough consecutive sequences of members, relate the remaining leader to null.

Example:

$leaders = [1,4,8,13];
$members = [2,3,5,6,7,9,10,11,12];

This is the result I want

$leaders = [
   1 => [2,3],
   4 => [5,6,7],
   8 => [9,10,11,12],
   13 => null
];

CodePudding user response:

Is this a solution for your question? I have assumed that you need to assign members to leaders up to the next leader number, i.e leader 1 is assigned to member 2,3. Next leader 4, is assigned members that have higher numbers than 4... i.e. 5,6,7 (but not higher than 8 - next leader), and so on...

$leaders = [1,4,8,13];
$members = [2,3,5,6,7,9,10,11,12];

$current_leader = current($leaders);
$next_leader = next($leaders);
$group = [];
foreach ($members as $member) {
    if ($member < $next_leader) {
        $group[$current_leader][] = $member;
    } else {
        $group[$next_leader][] = $member;
        $current_leader = $next_leader;
        $next_leader = next($leaders);
    }
}
if ($next_leader) {
    $group[$next_leader] = null;
}

// Output the result
echo "<pre>";
print_r($group);

Note that this solution won't solve if you have more leaders above 13... But it may be a help on the way :)

CodePudding user response:

Loop the members array and conditional declare a reference variable that will point to the key in the result array which relates to the first leasers value. Using array_shift() will isolate the first leader and consume it (which will present a new first leader the next time a new leader value is needed.

When finished iterating the members array, try to loop the leaders array. If there are any remaining leaders, they will be pushed into the result array as keys to null values.

Code: (Demo)

$result = [];
$lastMember = null;
foreach ($members as $member) {
    if ($lastMember === null || $lastMember !== $member - 1) {
        unset($ref);
        $result[array_shift($leaders)] = &$ref;
    }
    $ref[] = $lastMember = $member;
}
foreach ($leaders as $leader) {
    $result[$member] = null;
}
var_export($result);
  • Related