PHP Mysql while循环为带限制的空行设置默认数组值
我有两组横幅广告和两组横幅广告。数据库是这样的PHP Mysql while循环为带限制的空行设置默认数组值,php,arrays,multidimensional-array,while-loop,Php,Arrays,Multidimensional Array,While Loop,我有两组横幅广告和两组横幅广告。数据库是这样的 Array ( [1] => Array ( [1] => Array ( [type] => 2 [url] => https://example.com/banner.png [count] => 1
Array
(
[1] => Array
(
[1] => Array
(
[type] => 2
[url] => https://example.com/banner.png
[count] => 1
)
[2] => Array
(
[type] => 2
[url] => https://example.com/images.png
[count] => 2
)
[3] => Array
(
[type] => default
[count] => 3
)
)
[2] => Array
(
)
)
团体广告
横幅广告
此代码用于显示基于其组的所有横幅广告
$res_arr = array();
$stmt = $conn->prepare("SELECT * FROM groups_ads");
$stmt->execute();
$stmt->setFetchMode(PDO::FETCH_ASSOC);
while ($res = $stmt->fetch())
{
$result = array();
$max_slot = $res['max_places'];
$count = 0;
$banners = array();
$stmts = $conn->prepare('
SELECT * FROM banner_ads
WHERE group_id = "'.$res['id'].'"
');
$stmts->execute();
$stmts->setFetchMode(PDO::FETCH_ASSOC);
while ($count < $max_slot && $banner = $stmts->fetch()){
$count++;
if($banner){
$banners = array(
"type" => 2,
"url" => $banner['url_images'],
"count" => $count
);
}else{
$banners = array(
"type" => "default",
"count" => $count
);
}
$result[$count] = $banners;
}
$res_arr[$res['id']] = $result;
}
因为我的数据库中有两个横幅广告,在第一组
问题是,如何根据最大位置填充空行?
在数据库组中,组1的最大位置为3。但在数据库中,横幅广告只有两个横幅。那么,我如何将空的位置填充到默认字符串中呢?所以结果是这样的
Array
(
[1] => Array
(
[1] => Array
(
[type] => 2
[url] => https://example.com/banner.png
[count] => 1
)
[2] => Array
(
[type] => 2
[url] => https://example.com/images.png
[count] => 2
)
[3] => Array
(
[type] => default
[count] => 3
)
)
[2] => Array
(
)
)
感谢您的帮助。如果在while循环条件中删除$banner上的测试,您将确保始终为每个数组填充$max\u slots值。替换:
while ($count < $max_slot && $banner = $stmts->fetch()){
$count++;
if($banner){
与
Array
(
[1] => Array
(
[1] => Array
(
[type] => 2
[url] => https://example.com/banner.png
[count] => 1
)
[2] => Array
(
[type] => 2
[url] => https://example.com/images.png
[count] => 2
)
[3] => Array
(
[type] => default
[count] => 3
)
)
[2] => Array
(
)
)
while ($count < $max_slot && $banner = $stmts->fetch()){
$count++;
if($banner){
while ($count < $max_slot) {
$count++;
if ($banner = $stmts->fetch()) {