1

There is the following array:

arr1 = array(array('xxx',3),array('yyy',2));

I need to transform it into the array arr2, where the number of occurrence of each entry is equal to the 2nd column value in array arr1. For instance, for the above given arr1, arr2 should be the following:

arr2 = array(array('xxx'),array('xxx'),array('xxx'),array('yyy'),array('yyy'));

I wrote the following code, but my question is: Is it possible to do the same in a simpler way?

for ($i=0; $i<count($arr1); $i++) {
  for ($j=0; $j<$arr1[i][1]; $j++) {
     $arr2[] = array($arr1[0]);
  }
}
1
  • 3
    A missing $ before arr2, i, and j ?
    – jadkik94
    May 19, 2012 at 16:31

2 Answers 2

3

I think a foreach is simpler and easier to read.

$arr1 = array(array('xxx', 3), array('yyy', 2));
$arr2 = array();

foreach ($arr1 as $arr)
{
    for ($i = 0; $i < $arr[1]; $i++)
    {
        $arr2[] = array($arr[0]);
    }
}
2
  • Probably you mean $arr2[] = array($arr[$i]); May 19, 2012 at 16:39
  • @KlausosKlausos I don't think he does - each $arr is an array with 2 items. $arr[0] is what you want to repeat.
    – Gareth
    May 19, 2012 at 16:41
1
foreach ($arr1 as $entry) {
    $arr2[] = array_fill(0, $entry[1], array($entry[0]));
}
$arr2 = call_user_func_array('array_merge', $arr2);

I wouldn't use it though. It's much less readable.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.