Reputation: 16040
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]);
}
}
Upvotes: 1
Views: 120
Reputation: 4393
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]);
}
}
Upvotes: 3
Reputation: 31813
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.
Upvotes: 1