2017-02-10 61 views
5

我有一個屬性表,它有六列。用戶上傳的照片和圖像名稱存儲在列中。計數行中的空列

現在我想要計算每個空行的列數。

我已經能夠做到這一點,但代碼看起來太長,我想編寫高效的代碼,有沒有一種方法來有效地重寫以下內容。

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; 
    } 

} 

回答

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非空值

+0

有更多的數據來,有更多的專欄,但我想檢查只有這六列... – DragonFire

+0

這也是工作 – DragonFire

+0

如果我們想要得到結果是 - 有多少字段不是空的... – DragonFire

1

的計數試試這個代碼

while($data=$select->fetch()): 
    $imagecounter = 0; 
    for($i=1; $i<=6; $i++) 
     if(!empty($data["property_image$i"])) 
      $imagecounter++; 

    echo $imagecounter; 
endwhile; 
+0

@DragonFire:這個代碼呢? – bfahmi

+0

由於兩個循環而耗費時間意義上的不好代碼 –

+0

這是工作 – DragonFire

1

執行列名h作爲其規則?

假設它是 'property_image {數}'

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

代碼未經測試。 讓我知道,如果它不工作