我有一个属性表,它有六列。用户上传照片和图像名称存储在列中。
现在我想计算每一行为空的列数。
我已经能够做到这一点,但代码看起来太长了,我想编写高效的代码,有没有办法有效地重写以下内容。
while($data=$select->fetch()){
$imagecounter=0;
if ($data['property_image1'] !== "" && $data['property_image2'] !== "" && $data['property_image3'] !== "" && $data['property_image4'] !== "" && $data['property_image5'] !== "" && $data['property_image6'] !== "") {
echo $imagecounter=6;
} else if ($data['property_image1'] !== "" && $data['property_image2'] !== "" && $data['property_image3'] !== "" && $data['property_image4'] !== "" && $data['property_image5'] !== "") {
echo $imagecounter=5;
} else if ($data['property_image1'] !== "" && $data['property_image2'] !== "" && $data['property_image3'] !== "" && $data['property_image4'] !== "") {
echo $imagecounter=4;
} else if ($data['property_image1'] !== "" && $data['property_image2'] !== "" && $data['property_image3'] !== "") {
echo $imagecounter=3;
} else if ($data['property_image1'] !== "" && $data['property_image2'] !== "") {
echo $imagecounter=2;
} else if ($data['property_image1'] !== "") {
echo $imagecounter=1;
}
}
答案 0 :(得分:2)
您可以执行以下操作: -
while($data=$select->fetch()){
$data1 = array($data['property_image1'],$data['property_image2'],$data['property_image3'],$data['property_image4'],$data['property_image5'],$data['property_image6']);
$count = count($data1); // count of original array
$count1 = count(array_filter($data1)); // remove empty indexes and count the values
echo "empty columns number is :-".($count-$count1);
}
注意: - $count1
是非空值的计数
答案 1 :(得分:1)
试试这段代码
while($data=$select->fetch()):
$imagecounter = 0;
for($i=1; $i<=6; $i++)
if(!empty($data["property_image$i"]))
$imagecounter++;
echo $imagecounter;
endwhile;
答案 2 :(得分:1)
列名是否有规则?
假设它是'property_image {number}'
while($row=$result->fetch()) {
$count = 0;
for($i=0; $i<6; $i++) {
if($row['property_image'.$i]==NULL)
$count++;
}
echo "empty columns number is :-".($count);
}
代码未经过测试。 如果它不起作用,请告诉我