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]);
}
}
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]);
}
}