[英]How to get values separated with comma from database using PHP
我有四個名為逗號的文件,它們分隔在數據庫的一個字段中,例如file1
, file2
, file3
, file4
。 視上傳的文件而定。 用戶最多可以上傳4個文件,最少可以上傳一個文件。 但是我沒辦法。 我使用了explode,但是花費的時間太長。
我正在使用此代碼:
$imagefiles = $row["imagefiles"];
$cutjobs = explode(",", $imagefiles);
$cutjobs1 = count($cutjobs);
$image1 = $cutjobs[0];
$image2 = $cutjobs[1];
$image3 = $cutjobs[2];
$image4 = $cutjobs[3];
if (empty($image1)) {
$imagefiles1 = "";
} else {
$imagefiles1 = 'http://projects.santabantathegreat.com/glassicam/uploads/'.$registerid.
"/".$viewjobsid.
"/".$image1;
}
if (empty($image2)) {
$imagefiles2 = "";
} else {
$imagefiles2 = 'http://projects.santabantathegreat.com/glassicam/uploads/'.$registerid.
"/".$viewjobsid.
"/".$image2;
}
if (empty($image3)) {
$imagefiles3 = "";
} else {
$imagefiles3 = 'http://projects.santabantathegreat.com/glassicam/uploads/'.$registerid.
"/".$viewjobsid.
"/".$image3;
}
if (empty($image4)) {
$imagefiles4 = "";
} else {
$imagefiles4 = 'http://projects.santabantathegreat.com/glassicam/uploads/'.$registerid.
"/".$viewjobsid.
"/".$image4;
}
}
$data[] = array( 'imagearray' => array($imagefiles, $imagefiles1, $imagefiles2, $imagefiles3));
}
echo json_encode($data);
}
我得到這樣的輸出:
[{"imagearray":["http:\/\/projects.santabantathegreat.com\/glassicam\/uploads\/60\/30\/file1.jpg","http:\/\/projects.santabantathegreat.com\/glassicam\/uploads\/60\/30\/file2.jpg",""]}]
如果您看到此imageArray的最后一個正在獲取“”,則表示file1
, file2
, file3
, file4
某個名稱丟失,因此我想顯示是否沒有文件名,這意味着我不想使用“”顯示空值
我有一個包含file1,file2,file3,file4的字段,因此,我們將擁有file1,file3,然后剩余的將不在那里,所以我想計算用逗號分隔的文件名,如果file1存在,則應打印,如果file3沒有它不應顯示為“”
您本可以使用split()
,但在PHP 5.3.0中已棄用了它。 因此,您只剩下:
explode()
更快,因為它不會基於正則表達式進行拆分,因此不必由正則表達式分析器分析字符串。 要么
preg_split()
,速度更快,並使用PCRE正則表達式進行正則表達式拆分。 使用preg_split()
您可以執行以下操作:
<?php
$encoded_data = json_encode($data);
$images = preg_split('/,/', $encoded_data->imagearray);
?>
我會說explode()
更適合於此。
<?php
$encoded_data = json_encode($data);
$images = explode(',', $encoded_data->imagearray);
print_r($images);
?>
首先,數組中不應有空值。 但是,如果您仍然有任何空值,則可以在此處使用preg_split()
這樣的值。
同樣,您可以使用array_filter()處理值(null, false,'',0)
除去:
print_r(array_filter($images));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.