1

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 Answers 2

3

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));
}
Sign up to request clarification or add additional context in comments.

Comments

1

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

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.