2015-11-04 84 views
1

下面的代码给我带来了一系列图像。我有15个字段:“img1”,“img2”,“img3”等。PHP + json:不包含空字段

有时不是所有的字段都有数据。我不想将它们包含在数组中。有没有办法将这些空字段保存在数组之外?

<?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); 


?> 

回答

3

大图片

你需要,而不是标准化与像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); 
?> 
+0

我建立一个Android应用程序原型来搜索了地产公司分贝,得到的公寓,房子的图片,等你觉得这些数据库使用与引用表? –

+0

@madsongr我不知道如何构建数据库。如果该表是您创建的表,那么您应该重构它。如果没有,我的答案中的循环将非常好地工作。 –

+0

是的两个答案的工作。非常感谢!作为原型,我在同一张表中构建了一个带有图像的简单数据库。现在要解决其他情况。再次感谢。 –

1

只需修改阵列填充器使用IF语句:

if($row['img1']) $images[] = array('images' => $row['img1']; 

所以,如果有东西在它只会添加一个。