[英]Generate Array elements from array with elements as key value php
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所以我可以拥有所有数据并将数组拆分为具有 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?
}
Use a nested for
loop.使用嵌套的for
循环。
$result = [];
foreach ($array_caselle as $key => $count) {
for ($i = 0; $i < $count; $i++) {
$result[] = $key;
}
}
or use array_fill()
:或使用array_fill()
:
$result = [];
foreach ($array_caselle as $key => $count) {
$result = array_merge($result, array_fill(0, $count, $key));
}
You can use array_fill
with array_merge
您可以将array_fill
与array_merge
array_fill
使用
$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如果您的 PHP 版本不支持 splat 运算符,您可以使用
$res=[];
foreach($a as $k => $v){
$res = array_merge($res,array_fill(0, $v, $k));
}
Using foreach
and for
使用foreach
和for
$res=[];
foreach($a as $k => $v){
for($i=0;$i<$v;$i++) $res[] = $k;
}
Working example :- https://3v4l.org/AJnfn工作示例:- https://3v4l.org/AJnfn
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.