Generate Array elements from array with elements as key value php

74 views Asked by At

I have an Array I want to rewrite with many elements as the value of any key

Array
(
    [cap] => 3
    [shirt] => 2
    [tatuaggio] => 1
    [badge] => 2
)

and I want this output

Array
(
    cap,cap,cap,shirt,shirt,tatuaggio,badge,badge
)

so I can have all data and split the array in many array with 7 elements When I have the loop

foreach ($array_caselle as $k => $v) {
    //with this I have access to all key, but how can I do an other foreach for the value of each key?
  }
2

There are 2 answers

0
Barmar On BEST ANSWER

Use a nested for loop.

$result = [];
foreach ($array_caselle as $key => $count) {
    for ($i = 0; $i < $count; $i++) {
        $result[] = $key;
    }
}

or use array_fill():

$result = [];
foreach ($array_caselle as $key => $count) {
    $result = array_merge($result, array_fill(0, $count, $key));
}
0
Rakesh Jakhar On

You can use array_fill with array_merge

$res=[];
foreach($a as $k => $v){
  $res[] = array_fill(0, $v, $k);
}
print_r(array_merge(...$res));// splat operator

If your PHP version is not supporting splat operator you can use

$res=[];
foreach($a as $k => $v){
 $res = array_merge($res,array_fill(0, $v, $k));
}

Using foreach and for

$res=[];
foreach($a as $k => $v){
 for($i=0;$i<$v;$i++) $res[] = $k;
}

Working example :- https://3v4l.org/AJnfn