Zaffar Saffee
Zaffar Saffee

Reputation: 6305

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],
]

Upvotes: 2

Views: 1380

Answers (3)

mickmackusa
mickmackusa

Reputation: 48031

For circular array access, count and cache the element count of the keys array. While looping, use a modulus operator to return the remainder of the division between the current index and the keys count. Demo

$values = range(1, 12);
$keys = ['itema', 'itemb', 'itemc', 'itemd'];
$count = count($keys);

$result = [];
foreach ($values as $i => $v) {
    $result[$keys[$i % $count]][] = $v;
}
var_export($result);

Output:

array (
  'itema' => 
  array (
    0 => 1,
    1 => 5,
    2 => 9,
  ),
  'itemb' => 
  array (
    0 => 2,
    1 => 6,
    2 => 10,
  ),
  'itemc' => 
  array (
    0 => 3,
    1 => 7,
    2 => 11,
  ),
  'itemd' => 
  array (
    0 => 4,
    1 => 8,
    2 => 12,
  ),
)

Upvotes: 0

Relequestual
Relequestual

Reputation: 12355

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.

Upvotes: 2

Victor Kuznetsov
Victor Kuznetsov

Reputation: 284

Something like this:

$a = array(1,2,3,4,5,6,7,8,9,10,11,12);
$b = array('a', 'b', 'c', 'd');
$aLength = count($a);
$bLength = count($b);
$c = array();
for ($i = 0; $i < $bLength; ++$i) {
    $c[$b[$i]] = array();
    $j = $i;
    while ($j < $aLength) {
        $c[$b[$i]][] = $a[$j];
        $j += $bLength;
    }
}
var_dump($c);

Upvotes: 0

Related Questions