我正在开发laravel 5.3,这是我的代码
$arrayData = array();
foreach ($stats as $key => $row) {
$arrayData[] = array(
'number' => $row->no,
'level' => $row->total_sent,
'past' => $row->past,
);
}
如果我dd($arrayData)
输出为
array:3 [▼
0 => array:3 [▼
"no" => "4"
"level" => 3
"past" => "3"
]
1 => array:3 [▼
"no" => "6"
"level" => 3
"past" => "3"
]
2 => array:3 [▼
"no" => "9"
"level" => 3
"past" => "3"
]
]
以上分别为4,6,9。 我想最终输出应该包含完整的数据。 如果没有退出,其他明智的数字应为零。
在上述情况下,所需的输出为 在缺失位置,将有一个零值的正确数字
array:11 [▼
0 => array:3 [▼
"no" => "0"
"level" => 0
"past" => "0"
]
1 => array:3 [▼
"no" => "1"
"level" => 0
"past" => "0"
]
2 => array:3 [▼
"no" => "2"
"level" => 0
"past" => "0"
]
3 => array:3 [▼
"no" => "3"
"level" => 0
"past" => "0"
]
4 => array:3 [▼
"no" => "4"
"level" => 3
"past" => "3"
]
5 => array:3 [▼
"no" => "5"
"level" => 0
"past" => "0"
]
6 => array:3 [▼
"no" => "6"
"level" => 3
"past" => "3"
]
7 => array:3 [▼
"no" => "7"
"level" => 0
"past" => "0"
]
8 => array:3 [▼
"no" => "8"
"level" => 0
"past" => "0"
]
9 => array:3 [▼
"no" => "9"
"level" => 3
"past" => "3"
]
10 => array:3 [▼
"no" => "10"
"level" => 0
"past" => "0"
]
希望问题很清楚
提前致谢
答案 0 :(得分:5)
使用零填充值启动数组:
for ($i=0; $i <= 10; $i++) {
$arrayData[$i] = [
"no" => "$i",
"level" => 0,
"past" => "0",
];
}
foreach ($stats as $key => $row) {
$arrayData[$row->no] = [
'no' => $row->no,
'level' => $row->total_sent,
'past' => $row->past,
];
}
答案 1 :(得分:0)
如果您不知道最大no
值,则需要获取它。然后使用$arrayData
函数
array_fill
$stats = collect($stats);
$arrayData = [];
$maxNo = $stats->max('no');
$arrayData = array_fill(0, $maxNo, [
'number' => 0,
'level' => 0,
'past' => 0
]);
$stats->each(function($row) use(&$arrayData){
$arrayData[$row->no] = [
'number' => $row->no,
'level' => $row->total_sent,
'past' => $row->past,
];
});