2

I'm trying to divide an array into a multiple-dimensional array with 2 'elements' in each contained array.

So far I've only been able to divide them into a specified number of chunks, but as the number of elements are determined from a foreach loop and call to the database, I'm struggling to divide them into multiples of 2.

foreach ($_POST as $key)
{
    $data[] = $key;
}

echo '<pre>';
  print_r(partition($data, $i));
echo '</pre>';



function partition(Array $list, $p) 
{
  $listlen = count($list);
  $partlen = floor($listlen / $p);
  $partrem = $listlen % $p;
  $partition = array();
  $mark = 0;

  for($px = 0; $px < $p; $px ++)
  {
    $incr = ($px < $partrem) ? $partlen + 1 : $partlen;
    $partition[$px] = array_slice($list, $mark, $incr);
    $mark += $incr;
  }

  return $partition;
}

The desired output would be like this ...

Array
(
  [0] => Array
  (
     [0] => img.jpg
     [1] => http://google.com
  )
  [1] => Array
  (
     [0] => img.jpg
     [1] => http://google.com
  )
  [2] => Array
  (
     [0] => img.jpg
     [1] => http://google.com
  )
)

Any help would be appreciated.

Thanks

2
  • 3
    it would be useful if you added a simple example of at least the expected result Commented Oct 13, 2017 at 8:08
  • Apologies. I've added an example of the desired output Commented Oct 13, 2017 at 8:14

3 Answers 3

3

Just use the array_chunk function (-;

Example:

<?php
print_r(array_chunk($data, 2));
Sign up to request clarification or add additional context in comments.

Comments

1

Try array_chunk

see below solution:

foreach (range(1, 10) as $key)
{
    $data[] = $key;
}
$i = 2;
echo '<pre>';
print_r(partition($data, $i));
echo '</pre>';

function partition(Array $list, $p)
{
    $partition = array_chunk($list, $p, true);

    return $partition;
}

Output:

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

    [1] => Array
        (
            [2] => 3
            [3] => 4
        )

    [2] => Array
        (
            [4] => 5
            [5] => 6
        )

    [3] => Array
        (
            [6] => 7
            [7] => 8
        )

    [4] => Array
        (
            [8] => 9
            [9] => 10
        )

)

Comments

0

array_chunk does this for you.

foreach ($_POST as $key)
{
    $data[] = $key;
}
var_dump(array_chunk($data, 2));

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.