簡體   English   中英

使用元素作為鍵值php從數組生成數組元素

[英]Generate Array elements from array with elements as key value 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?
  }

使用嵌套的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));
}

您可以將array_fillarray_merge array_fill使用

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

如果您的 PHP 版本不支持 splat 運算符,您可以使用

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

使用foreachfor

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

工作示例:- https://3v4l.org/AJnfn

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM