php - 从以元素为键值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));
}
推荐阅读
- python - 如果 .iloc 和 .loc 似乎不起作用,如何替换 df.ix?
- django - Django可以一一返回空的表单字段吗?
- opencv - 如何让 FFMPEG 从 OpenCV 获取帧并将它们流式传输到 HTTP 服务器
- go - Effective Go 中的客户端请求处理程序示例导致死锁?
- php - 如何在登录时使用 getLastAuthenticationError() 检索错误消息?
- javascript - 如何从firestore网站通过文档ID获取特定的字段数据
- r - 在 R 中将天数转换为年数
- reactjs - React Native:我按下文本输入并出现键盘并在使用 Keyboard.addListener 时自动关闭一次
- google-chrome - 如何在 Chrome DevTools 网络面板中否定 `is:` 过滤器属性
- c - 如何通过指针访问结构的第二个成员?