2017-04-14 25 views
2

我試圖合併陣列。至少據我所知是兩個數組。但是PHP返回一個錯誤,說第一個不是數組。合併到一起的陣列

我的最終目標是要上傳的圖片,然後讓我在文本文件中的現有數據,追加新的結果對現有數據的末端,然後將它寫回數據庫。這樣,每次上傳新圖像時都不會重寫文件,因此您可以繼續上傳越來越多的圖像。

這裏是我的PHP:

<?php 
$sFileName = "imgDB.txt"; 
$temp = "temp.txt"; 

for($i=0 ; $i < count($_FILES) ; $i++){ 
move_uploaded_file($_FILES['file-'.$i]['tmp_name'] , "img/". $_FILES['file- 
'.$i]['name']); 
} 


// Get the content of the file! 
$sImgs = file_get_contents($sFileName); //gets a string from the file. 
$ajImgs = json_decode($sImgs); //converts the string to an array. 


$aOutPut = array_merge ($ajImgs, $_FILES); 

$aSendToFile = json_encode($aOutPut, JSON_PRETTY_PRINT | 
JSON_UNESCAPED_UNICODE); 
file_put_contents($sFileName, $aSendToFile); 
+4

將'true'作爲第二個參數傳遞給'json_decode()'以獲取數組。否則你得到一個對象。 –

回答

1

這個問題可能是在這裏:

$ajImgs = json_decode($sImgs); 

默認情況下,json_decode()返回一個對象。如果你想要一個數組,你可以通過布爾true作爲可選的第二個參數:

$ajImgs = json_decode($sImgs,1); 

docs

assoc命令

爲真時,返回的對象將轉換成關聯陣列。

但是,如果文件「imgDB.txt」爲空,也可能會得到布爾falsejson_decode()回來,這樣你就可以檢查確保你有一個這樣的數組:

$ajImgs = json_decode($sImgs,1) ?: array(); 

這是簡寫:

if (json_decode($sImgs,1) != false) { 
    $ajImgs = json_decode($sImgs,1); 
} else { 
    $ajImgs = array(); 
} 

UPDATE:

要解決圖像在JSON覆蓋掉了,同時還避免受騙者我建議建立一個新的陣列,使用文件名作爲關鍵字:

// initialize a new array for use below 
$files = array(); 
for($i=0 ; $i < count($_FILES) ; $i++){ 
    /* for some reason your application posts some empty files 
     without going to deep into the javascript side, 
     here is a simple way to ignore those */ 
    if (empty($_FILES['file-'.$i]['size'])) continue; 
    move_uploaded_file($_FILES['file-'.$i]['tmp_name'] , "img/". $_FILES['file-'.$i]['name']); 

    // now we build a new array using filenames as array keys 
    $files[$_FILES['file-'.$i]['name']] = $_FILES['file-'.$i]; 

    // if you don't care about dupes you can use a numeric key like this 
    // $files[] = $_FILES['file-'.$i]; 
} 

// now do your merge with this new array 
$aOutPut = array_merge ($ajImgs, $files); 

上述內容已經過測試,爲我工作。有可能是一個更好的方式來處理這個問題,像直接添加文件到解碼JSON,但重寫整個應用程序超出了這個問題的範圍。

+0

感謝@ billynoah,解決了我的錯誤:)。然而它仍然不太有效。你或其他人知道我的數組爲什麼不合並。我的代碼會在每次運行時覆蓋數組,而不是將它們放在一起。 – Wonx2150

+1

@ Wonx2150 - 如果鍵是字符串且相同,則數組合並將使用後者覆蓋前者。看起來你正在使用'file-1','file-2'等東西。如果你可以改變它們來簡單地使用數字鍵,'array_merge()'將負責重新索引它們。如果不是,你需要做一些重命名它們,使它們是唯一的。不知道如何生成$ _FILES,很難更具體。 – billynoah

+0

如果你不介意,我可以使用一些幫助。我試圖將它們改爲數字鍵,儘管我可能在錯誤的軌道上。我試圖讓它們高於數組的值或給它們隨機數字作爲文件名。沒有一個技巧。 這裏是文件的URL,因爲它可能更容易,如果你看看文件,而不是代碼段。[鏈接](http://wonx.dk/imgUploader/ImgUploader.zip) – Wonx2150

0

您需要添加第二個參數json_decode()。

$ajImgs = json_decode($sImgs, true);