Search code examples
phparraysmultidimensional-arraygroupingcircular-reference

Group flat array values using a flat array of keys over and over as needed


I have a flat array of values:

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

and another array to be used as keys, but it is not always long enough to pairs with the previous array of values.

$keys = ['itema', 'itemb', 'itemc', 'itemd'];

I want to distribute the first array as values to a new array where the keys array are circularly accessed (after the last is used, then use the first) so that my output looks like

[
    'itema' => [1, 5, 9],
    'itemb' => [2, 6, 10],
    'itemc' => [3, 7, 11],
    'itemd' => [4, 8, 12],
]

Solution

  • Assuming the first array you talk of is a multi dimensional array, as in

    $firstArray = { a={1,2,3},b={1,2,3} };
    

    What you need to do is loop through each array and create a new one in the process.

    $masterArray = {itema,itemb,itemc,itemd};
    
    
    $newArray = new Array();
    for ($i = 0; $i<$masterArray.length; $i++) {
       for ($j = 0; $j<$firstArray.length; $j++){
          $newArray[$i] = $masterArray[$i]=>$firstArray[$j][$i];
       }
    }
    
    var_dump($newArray);
    

    I haven't tested the code myself, so I can't say it's perfect, but that's basically what you want to do. Feel free to ask questions.

    Edit: As a result of a discussion, I found out that using the array chunk function did what the OP wanted, but not what the question asked.