2016-09-23 90 views
-1

我已經搜索了答案,但沒有解決我的問題。如何使用PHP輸出json數組?

如何讓輸出像這樣?
在此先感謝

我想離開這個下面

標題:第一個冠軍
標籤:標籤-A-1,TAG-A-2,標籤-A-3

標題:第二標題
標籤:標籤-b-1,標籤-b-2,標籤-b-3

名稱:第三標題
標籤:標籤-C-1,標籤-C-2,標籤 - c-3

file.json

{ 
"videos": [ 
    { 
     "title": "First Title", 
     "tags": [ 
      { 
       "tag_name": "tag-a-1" 
      }, 
      { 
       "tag_name": "tag-a-2" 
      }, 
      { 
       "tag_name": "tag-a-3" 
      } 
     ], 
     "publish_date": "2016-09-12 16:40:14" 
    }, 
    { 
     "title": "Second Title", 
     "tags": [ 
      { 
       "tag_name": "tag-b-1" 
      }, 
      { 
       "tag_name": "tag-b-2" 
      }, 
      { 
       "tag_name": "tag-b-3" 
      } 
     ], 
     "publish_date": "2016-09-12 16:40:14" 
    }, 
    { 
     "title": "Third Title", 
     "tags": [ 
      { 
       "tag_name": "tag-c-1" 
      }, 
      { 
       "tag_name": "tag-c-2" 
      }, 
      { 
       "tag_name": "tag-c-3" 
      } 
     ], 
     "publish_date": "2016-09-12 16:40:14" 
    } 
] 

}

output.php

<?php 
    ini_set('display_errors', 1); 
    $html = "file.json"; 
    $html = file_get_contents($html); 
    $videos = json_decode($html, true); 

     foreach ($videos['videos'] as $video) { 
      $title = $video['title']; 

      foreach ($video['tags'] as $tags) { 
       $tags = $tags['tag_name']; 

      echo 'Title: ' . $title . '<br />'; 
      echo 'Tags: ' . $tags . ', <br /><br />'; 

      } 
     } 

回答

1

你的第二次迭代似乎是錯誤的。您應該在第一個循環中打印標題/標籤。

foreach ($videos['videos'] as $video) { 
     $title = $video['title']; 
     $tags = array(); // reset it every new item to avoid race-condition on empty one. 

     foreach ($video['tags'] as $tags) { 
      $tags[] = $tags['tag_name']; 
      // ^also add new elements here 
     } 

     echo 'Title: ' . $title . '<br />'; 
     echo 'Tags: ' . implode(',', $tags) . '<br /><br />'; 
     //   ^also join your tags 
    } 
+0

非常感謝你 – Anwar