下面的代码给我带来了一个图像数组。我有15个字段:"img1"、"img2"、"imm3"等等
有时并不是所有字段都有数据。我不想将它们包括在数组中。有没有办法将这些空字段保留在数组之外?
<?php
include_once 'db_connect.php';
$i_id = $_POST["imovel_id"];
$sql = "SELECT * FROM iMoveis WHERE imovel_id='$i_id'";
$result = mysqli_query($mysqli, $sql);
$response = array();
$images = array();
while($row = mysqli_fetch_assoc($result)){
$images[] = array('images' => $row['img1']);
$images[] = array('images' => $row['img2']);
$images[] = array('images' => $row['img3']);
$images[] = array('images' => $row['img4']);
$images[] = array('images' => $row['img5']);
$images[] = array('images' => $row['img6']);
$images[] = array('images' => $row['img7']);
$images[] = array('images' => $row['img8']);
$images[] = array('images' => $row['img9']);
$images[] = array('images' => $row['img10']);
$images[] = array('images' => $row['img11']);
$images[] = array('images' => $row['img12']);
$images[] = array('images' => $row['img13']);
$images[] = array('images' => $row['img14']);
$images[] = array('images' => $row['img15']);
}
$response['posts'] = $images;
echo json_encode($response, JSON_UNESCAPED_SLASHES);
?>
大图
您需要规范化数据,而不是使用名称类似img15
的字段。将图像放在另一个表中,并参考imovel_id
。规范化的数据会让这件事变得容易得多。
破解你的问题
使用当前的表结构,您别无选择,只能执行大量的if
语句(或对数据进行循环)。类似这样的东西:
<?php
include_once 'db_connect.php';
$i_id = $_POST["imovel_id"];
$sql = "SELECT * FROM iMoveis WHERE imovel_id='$i_id'";
$result = mysqli_query($mysqli, $sql);
$response = array();
$images = array();
while($row = mysqli_fetch_assoc($result)){
for ($index = 1; $index <= 15; $index++) { // loop over the columns
if (!empty($row['img' . $index])) { // check for null or empty columns
$images[] = array('images' => $row['img' . $index]); // add only if there is data
}
}
}
$response['posts'] = $images;
echo json_encode($response, JSON_UNESCAPED_SLASHES);
?>
只需使用IF语句修改数组填充器:
if($row['img1']) $images[] = array('images' => $row['img1'];
因此,只有当里面有东西的时候,它才会添加那个。