如何用php制作输出json数组?

时间:2016-09-23 00:39:30

标签: php html arrays json tags

我找到了答案,但我的问题无法解决。

如何制作这样的输出?
提前致谢

我想在下面

标题:第一标题
标签:tag-a-1,tag-a-2,tag-a-3

标题:第二标题
标签:tag-b-1,tag-b-2,tag-b-3

标题:第三标题
标签:tag-c-1,tag-c-2,tag-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 />';

            }
        } 

2 个答案:

答案 0 :(得分: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
    } 

答案 1 :(得分:-1)

尝试使用json_decode功能。这似乎是要走的路。

http://php.net/manual/en/function.json-decode.php

我已经为您链接了文档。祝你好运。