Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array permutations as i need

Any of you may have done this type of combination i have mentioned below.

$data = array
(
    'a1' => array(7, 32,44),
    'a2' => array(4,44),
    'a3' => array(9,33,55)
);

This returns should be something like this if i try to retrieve n times. Suppose n=4 ( o to 3).

Array
(
    [0] => Array
        (
            [0] => 7  // from a1
            [1] => 4  // from a2
            [2] => 9  // from a3         
        )

    [1] => Array
        (
            [0] => 32
            [1] => 44
            [2] => 33           
        )

    [2] => Array
        (
            [0] => 44
            [1] => 4
            [2] => 55           
        )


    [3] => Array
        (
            [0] => 7
            [1] => 44
            [2] => 9           
        )
)

and so on....

like image 600
Rajesh Tandukar Avatar asked Feb 03 '26 01:02

Rajesh Tandukar


1 Answers

The % operation is your friend:

function foo($arr, $n) {
  $result = array();
  for ($i = 0; $i < $n; $i++) {
    $result[$i] = array_map(function($value) use ($i) {
      return $value[$i % count($value)];
    }, $arr);
  }
  return $result;
}

// usage:
var_dump(foo($data, 4));
like image 198
xdazz Avatar answered Feb 05 '26 15:02

xdazz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!