2017-05-25 91 views
0

我想加載我的數組與對象.csvPHP加載對象陣列

當我用強制字符串編寫JSON時,它的好和我的代碼工作正常。

當我嘗試製作對象並將它們加載到數組中時,新對象會覆蓋數組中的所有對象,並且我得到的數組中的所有對象都具有相同的值。對我的錯誤有什麼建議嗎?

最後,可變內容給出有效的JSON(沒有 '[]' 括號),但陣列contentArr給出陣列全相同對象的...

Here's的代碼:

  $content = ''; 
      $contentArr = array(); 
      $Obj = new stdClass(); 
      $count = 0; 
      while ($csv = fgetcsv($file,1000,",")) { 
        $content .= "{\"number\":\"".$csv[0]=Filter($csv[0])."\",\"message\":\"".$csv[1]."\"},"; 
        $count++; 
        $Obj -> number = $csv[0]=Filter($csv[0]); 
        $Obj -> message = $csv[1]; 
        $contentArr[] = $Obj; 
      } 
      $content = substr($content, 0, -1); 

回答

0

我希望這段代碼能幫到你

$openFile = fopen($file, "r"); 
while(!feof($openFile)){ 
    $csv = fgetcsv($file); 
    //your code here 
} 
fclose($openFile); 
+0

謝謝,但這不是問題,我得到了與裝載物品到數組的一個問題。從csv獲取信息很好。這只是我的代碼的一部分,因爲原始代碼長約400行。 –

0

解決了自己。

我的錯誤是我只改變鏈接到我在while循環之前創建的一個對象。當我將對象創建INTO移動到while循環時,我正在爲我加載到數組中的每個新數據創建一個新對象。

代碼:

 $content = ''; 
     $contentArr = array(); 
     //$Obj = new stdClass(); ----> this was my mistake 
     $count = 0; 
     while ($csv = fgetcsv($file,1000,",")) { 
       $content .= "{\"number\":\"".$csv[0]=Filter($csv[0])."\",\"message\":\"".$csv[1]."\"},"; 
       $count++; 
       $Obj = new stdClass();// ----> that's how it should be 
       $Obj -> number = $csv[0]=Filter($csv[0]); 
       $Obj -> message = $csv[1]; 
       $contentArr[] = $Obj; 
     } 
     $content = substr($content, 0, -1);