Question

I have a scenario where I need to loop between the two array as follow

 Array
    (
        [0] => 2
        [1] => 5
        [2] => 6
        [3] => 7
        [4] => 8
        [5] => 9
        [6] => 10
        [7] => 11
        [8] => 12
    )

    Array
    (
        [0] => 1234567890
        [1] => 2345678901
        [2] => 3456789012
        [3] => 4567890123
        [4] => 5678901234
        [5] => 6789012345
        [6] => 7890123456
        [7] => 8901234567
        [8] => 9012345678
        [9] => 9901234567
        [10] => 1234567890
        [11] => 2345678901
        [12] => 3456789012
    )

The first array is Users, and other is the mobile numbers where the User1 should be mapped to first mobile number, User2 should be mapped to second mobile number and goes on.

Here in the example I have 8 Users, so for 8th User, 8th mobile number will be mapped on and from 9th Mobile Number it should map to 1st user (I mean the loop until all the mobile numbers are assigned to the Users).

Was it helpful?

Solution

If you want to circularly assign the phone numbers to the users, Simply iterate the over each mobile number, get its index, find the equivalent index in the $users array by finding the remainder of the index with the size of the $users array. You can find the remainder using the Modulus(%) operator.
Try this -

$users = Array(2,5,6,7,8,9,10,11,12);
$mob =  Array(1234567890,2345678901,3456789012,4567890123,5678901234,6789012345,7890123456,8901234567,9012345678,9901234567,1234567890,2345678901,3456789012);
$res = Array();
$user_size = count($users);

//The main logic.
foreach($mob as $k=>$v){
    $res[ $users[$k % $user_size] ][] = $v;
}
var_dump($res);

/** OUTPUT 
array
  2 => 
    array
      0 => int 1234567890
      1 => float 9901234567
  5 => 
    array
      0 => float 2345678901
      1 => int 1234567890
  6 => 
    array
      0 => float 3456789012
      1 => float 2345678901
  7 => 
    array
      0 => float 4567890123
      1 => float 3456789012
  8 => 
    array
      0 => float 5678901234
  9 => 
    array
      0 => float 6789012345
  10 => 
    array
      0 => float 7890123456
  11 => 
    array
      0 => float 8901234567
  12 => 
    array
      0 => float 9012345678

OTHER TIPS

Try this:

<?php

$mapping = array();

while (!empty($phone)) {
    for ($i=0; $i < count($users); $i++) {
        empty($mapping[$users[$i]]) and $mapping[$users[$i]] = array();

        if (!empty($phone)) {
            $mapping[$users[$i]][] = array_shift($phone);
        }
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top