2017-05-26 156 views
-1

我有一個腳本循環並檢索一些指定的值並將它們添加到php數組中。然後我把它的值返回給該腳本:陣列中的PHP JSON陣列

[[{"id":1,"amount":2,"type":"0"}], [{"id":2,"amount":25,"type":"0"}]] 

這是造成問題,當我嘗試將數據解析到我的Android應用:

//Returns the php array to loop through 
$test_list= $db->DatabaseRequest($testing); 

//Loops through the $test_list array and retrieves a row for each value 
foreach ($test_list as $id => $test) { 

       $getList = $db->getTest($test['id']); 

       $id_export[] = $getList ; 

      } 

print(json_encode($id_export)); 

這將返回的JSON值。結果需要是這樣的:

[{"id":1,"amount":2,"type":"0"}, {"id":2,"amount":25,"type":"0"}] 

我意識到循環將數組添加到另一個數組中。我的問題是我如何循環php數組,並將所有這些值放入數組並將其輸出爲上面的JSON格式?

回答

1
當然

我覺得$的GetList包含數組你的數據庫中的列,

使用

$id_export[] = $getList[0] 

也許可以做一些檢查,以驗證您的$的GetList陣列是有效的1大小

1

$db->getTest()似乎是返回一個單個對象的數組,也許更多,然後您將添加到一個新的數組。請嘗試以下方法之一:

如果將永遠只能是一排,剛拿到0指數(簡單):

  $id_export[] = $db->getTest($test['id'])[0]; 

或獲取當前數組項:

  $getList = $db->getTest($test['id']); 

      $id_export[] = current($getList); //optionally reset() 

如果可能有不止一行,合併它們(無論是否更好和更安全的想法):

  $getList = $db->getTest($test['id']); 

      $id_export = array_merge((array)$id_export, $getList);