-3

I have code like this

$assoc = ['name','lastname','pesel'];
          $inputs = ['a', 'a', 'a', 'a', 'b', 'b', 'b', 'b',];
          $counter = 0;
          $internalcounter = 0;
          $zero = 0;
          $content = array();
          while ($counter < sizeof($inputs))
          {
              if($internalcounter == sizeof($assoc))
              {
                  $counter++;
                  $internalcounter = 0;
               
                  
              }
              else
              {
                  array_push($content, $inputs[$counter]);
                  $counter++;
                  $internalcounter++;
              }
          
           
          }
          var_dump($content);

It creates an array that looks like this:

array(6) { [0] => string(1) "a" [1] => string(1) "a" [2] => string(1) "a" [3] => string(1) "b" [4] => string(1) "b" [5] => string(1) "b" }

But I want to create a multi-dimensional array:

Array ( [0] => Array ( [0] => "a"  [1] => "a"  [2] => "a"  ) [1] => Array ( [0] => "b" [1] => "b" [2] => "b" )  )

How to add next array in $content?

2
  • 2
    What are your exact requirements? Do you want each sub-array to contain 3 values? Or only values of the same letter? Commented Mar 9, 2013 at 18:49
  • It's unclear how your code is outputting the array you say it's outputting, or how you expect it to output a multi-dimensional array with the same subset of inputs. You'll need to edit your question to include the code and/or business logic that specifies that, if you want an answer that actually works. Commented Jan 21 at 15:57

2 Answers 2

2

Alternative solution :

$assoc = ['name', 'lastname', 'pesel'];
$inputs = ['a', 'a', 'a', 'a', 'b', 'b', 'b', 'b'];
$content = array();
$i = 0;
foreach ($inputs as $key => $val) {
    $key += 1;
    if (($key < (sizeof($inputs)))) {
        if (($key % (sizeof($assoc) + 1) == 0)) {
            $content[++$i] = array();
        } else {
            $content[$i][] = $val;
        }
    }
}
var_dump($content);
Sign up to request clarification or add additional context in comments.

Comments

0
<?php

$assoc = ['name','lastname','pesel'];
$inputs = ['a', 'a', 'a', 'a', 'b', 'b', 'b', 'b'];
$counter = 0;
$internalcounter = 0;
$zero = 0;
$arrayIndex = 0;
$content = array();
$content[$arrayIndex] = array();

while ($counter < sizeof($inputs))
{
    if ($internalcounter == sizeof($assoc))
    {
        $counter++;
        $internalcounter = 0;

        if ($counter < sizeof($inputs))
            $content[++$arrayIndex] = array();
    }
    else
    {
        array_push($content[$arrayIndex], $inputs[$counter]);
        $counter++;
        $internalcounter++;
    }
}
var_dump($content);

1 Comment

your solution gives an additional empty array at the end.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.