2016-01-06 236 views
0

我要實現的JSON對象的下列格式輸出:JSON對象中的嵌套數組PHP

[ 
    { 
     "id":1, 
     "title":"Test Title", 
     "url":"http://test.com/", 
     "images":[ 
     { 
      "width":100, 
      "height":100, 
      "size":17000, 
      "url":"http://test.com", 
      "timestamp":14566698 
     }, 
     { 
      "width":100, 
      "height":100, 
      "size":160000, 
      "url":"http://test.com", 
      "timestamp":1451903339 
     } 
     ] 
    } 
] 

我從數據庫中收集的所有數據,並將其保存到變量和使用PHP創建JSON對象也包括一個環路它需要創建多個屬性:不過我實現輸出是不是我的意圖實現

for ($x = 1; $x <= 2; $x++) { 

    $JSONarray[] = array(
     'id' => $x, 
     'title' => $title, 
     'url' => $url, 
     'images' => array(
      'width' => $width, 
      'height' => $height, 
      'size' => $size, 
      'url' => urldecode($image), 
      'timestamp' => $timestamp 
     ), 
     array(
      'width' => $width2, 
      'height' => $height2, 
      'size' => $size2, 
      'url' => urldecode($image2), 
      'timestamp' => $timestamp2 
     ) 
    ); 
} 

echo json_encode($JSONarray, JSON_UNESCAPED_SLASHES); 

。那我得到的輸出是如下:

[ 
    { 
     "id":1, 
     "title":"Test Title", 
     "url":"http://test.com/", 
     "images":{ 
     "width":100, 
     "height":10, 
     "size":17000 , 
     "url":"http://test.com/", 
     "timestamp":14566698 
     }, 
     "0":{ 
     "width":100, 
     "height":100, 
     "size":160000 , 
     "url":"http://test.com/", 
     "timestamp":1451903339 
     } 
    } 
] 
+2

告訴我們你得到的輸出是什麼。我現在唯一能看到的就是你在'images'中缺少另一個數組,你需要''images'=> array(array(「。所以現在你可能在你的內部JSOnarray的索引0處得到秒圖像數組 – muffe

+1

'object'和'array'之間有區別,上面的JSON記法顯示一個對象數組作爲'images'元素的值,你試着將兩個數組插入到這個元素中,這是a)不同的和b)將不起作用。嘗試爲圖片創建對象,然後將_those_推入圖片數組中。 – arkascha

回答

2

注重圖像陣列,它必須看起來像這樣:

for ($x = 1; $x <= 2; $x++) { 

    $JSONarray[] = array(
     'id' => $x, 
     'title' => $title, 
     'url' => $url, 
     'images' => array(
      (object)array(
       'width' => $width, 
       'height' => $height, 
       'size' => $size, 
       'url' => urldecode($image), 
       'timestamp' => $timestamp 
      ), 
      (object)array(
       'width' => $width2, 
       'height' => $height2, 
       'size' => $size2, 
       'url' => urldecode($image2), 
       'timestamp' => $timestamp2 
      ) 
     ) 
    ); 
} 
0

我認爲你需要這個......

for ($x = 1; $x <= 2; $x++) { 

    $JSONarray[] = array(
     'id' => $x, 
     'title' => $title, 
     'url' => $url, 
     'images' => array(
      array(
       'width' => $width, 
       'height' => $height, 
       'size' => $size, 
       'url' => urldecode($image), 
       'timestamp' => $timestamp 
      ), 
      array(
       'width' => $width2, 
       'height' => $height2, 
       'size' => $size2, 
       'url' => urldecode($image2), 
       'timestamp' => $timestamp2 
      ) 
     ) 
    ); 
} 
echo json_encode($JSONarray, JSON_UNESCAPED_SLASHES);