0

Big picture: I'm needing to process data to find which combinations of the data (including repeats up to 4) meet criteria best.

From a basic array (1,2,3) and a $repeat_max=4 variable, I'm wanting to create an array like this programmatically since the array values will be dynamic. Please forgive any minor syntax errors, this is just a general concept. Please tell me if this is the worst idea ever. How do i loop through $data and create $indiv?

$data = array(1,2,3);

$indiv[0] => array ([0] => array([0] = 1),
                    [1] => array([0] = 1, [1] = 1),
                    [2] => array([0] = 1, [1] = 1, [2] = 1),
                    [3] => array([0] = 1, [1] = 1, [2] = 1, [3] = 1)),
$indiv[1] => array ([0] => array([0] = 2),
                    [1] => array([0] = 2, [1] = 2),
                    [2] => array([0] = 2, [1] = 2, [2] = 2),
                    [3] => array([0] = 2, [1] = 2, [2] = 2, [3] = 2)),
$indiv[2] => array ([0] => array([0] = 3),
                    [1] => array([0] = 3, [1] = 3),
                    [2] => array([0] = 3, [1] = 3, [2] = 3),
                    [3] => array([0] = 3, [1] = 3, [2] = 3, [3] = 3))

1 Answer 1

1

array_fill should do the trick:

$indiv = array();
foreach ($data as $val) {
  $tmp = array();
  for ($i = 0; $i < $repeat_max; $i++) $tmp[$i] = array_fill(0, $i + 1, $val);
  $indiv[] = $tmp;
}

With $data = [ 1, 2 ] and $repeat_max = 3 it looks like this:

Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [0] => 1
                )

            [1] => Array
                (
                    [0] => 1
                    [1] => 1
                )

            [2] => Array
                (
                    [0] => 1
                    [1] => 1
                    [2] => 1
                )

        )

    [1] => Array
        (
            [0] => Array
                (
                    [0] => 2
                )

            [1] => Array
                (
                    [0] => 2
                    [1] => 2
                )

            [2] => Array
                (
                    [0] => 2
                    [1] => 2
                    [2] => 2
                )

        )

)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.