首页 > 解决方案 > 从以元素为键值php的数组生成数组元素

问题描述

我有一个数组,我想用许多元素重写为任何键的值

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

我想要这个输出

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

所以我可以拥有所有数据并将数组拆分为具有 7 个元素的多个数组当我有循环时

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?
  }

标签: phparrays

解决方案


使用嵌套for循环。

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

或使用array_fill()

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

推荐阅读