Anwar Anwar - 2 months ago 6
JSON Question

How to make output json array with php?

I had searched the answer but there's no solution for my problem.

How make output like this?

Thanks in advance

I want out this below

Title: First Title

Tags: tag-a-1, tag-a-2,tag-a-3

Title: Second Title

Tags: tag-b-1, tag-b-2, tag-b-3

Title: Third Title

Tags: 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 />';

}
}

Answer

Your second iteration seems to be wrong. You should print title/tags in your first loop instead.

    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
    }