List json object returned by php

Asked

Viewed 496 times

2

I need a help, I am developing an app with HMTL5, JS, CSS that lists a pizza menu. My PHP returns an array that I use the json_encode() to be available in JSON format. So far everything then I have the following <div>:

<div class="card">
  <div class="logo">
   <img src"image1.jpg">
   <h2>title imagens</h2>
   <p>Outro titulo</p>
  </div>
</div>

My question is how can I build the structure above and make a loop to fill the elements with the data of the JSON object. In PHP you could only use foreach and give a echo $matriz['valor']. But as it is an App did not want to transmit much data.

  • please add a returned JSON example

  • I don’t understand the difficulty.. If you are already using an array, just continue using the array.. You encode the array in json format. And to read, just decode back as an associative array json_decode($array, true). This second parameter, when true, converts the json object in array.

3 answers

1

to post here a complement to William Urbano’s reply, with an alternative way to assemble the cards.

var imagens = [
    {
        "titulo": "Imagem 01",
        "descricao": "Lorem ipsum Culpa quis et",
        "img": "/images/img1.jpg"
    }, {
        "titulo": "Imagem 02",
        "descricao": "Lorem ipsum Laborum exercitation ea consequat ad",
        "img": "/images/img2.jpg"
    }, {
        "titulo": "Imagem 03",
        "descricao": "Lorem ipsum Magna incididunt proident culpa Duis",
        "img": "/images/img3.jpg"
    }, {
        "titulo": "Imagem 04",
        "descricao": "Lorem ipsum Ut proident dolor enim id",
        "img": "/images/img4.jpg"
    }, {
        "titulo": "Imagem 05",
        "descricao": "Lorem ipsum Ut fugiat ut veniam",
        "img": "/images/img5.jpg"
    }, {
        "titulo": "Imagem 06",
        "descricao": "Lorem ipsum Cupidatat enim Excepteur in",
        "img": "/images/img6.jpg"
    }, {
        "titulo": "Imagem 07",
        "descricao": "Lorem ipsum Occaecat esse cillum deserunt reprehenderit",
        "img": "/images/img7.jpg"
    }, {
        "titulo": "Imagem 08",
        "descricao": "Lorem ipsum Tempor dolor commodo fugiat elit in",
        "img": "/images/img8.jpg"
    }, {
        "titulo": "Imagem 09",
        "descricao": "Lorem ipsum Ut mollit eu nostrud Duis",
        "img": "/images/img9.jpg"
    }, {
        "titulo": "Imagem 10",
        "descricao": "Lorem ipsum Ut cillum in voluptate deserunt",
        "img": "/images/img10.jpg"
    }
];

var cards = document.getElementById("cards");
var tmplCard = document.getElementById("tmplCard").innerHTML;

cards.innerHTML = imagens.map(function (imagem) {
    return tmplCard.replace(/{(\w+)}/g, function(match, key){
        return imagem[key];
    });
}).join("");
console.log(teste);
<div id="cards">
    
</div>

<script id="tmplCard" type="text/template">
    <div class="card">
        <div class="logo">
            <img src="{img}" />
            <h2>{titulo}</h2>
            <p>{descricao}</p>
        </div>
    </div>
</script>

0

Try using the following JSON structure:

[{
    "id": 1,
    "nome": "Lorem ipsum Culpa quis et",
    "img": "/images/img1.jpg"
}, {
    "id": 2,
    "nome": "Lorem ipsum Laborum exercitation ea consequat ad",
    "img": "/images/img2.jpg"
}, {
    "id": 3,
    "nome": "Lorem ipsum Magna incididunt proident culpa Duis",
    "img": "/images/img3.jpg"
}, {
    "id": 4,
    "nome": "Lorem ipsum Ut proident dolor enim id",
    "img": "/images/img4.jpg"
}, {
    "id": 5,
    "nome": "Lorem ipsum Ut fugiat ut veniam",
    "img": "/images/img5.jpg"
}, {
    "id": 6,
    "nome": "Lorem ipsum Cupidatat enim Excepteur in",
    "img": "/images/img6.jpg"
}, {
    "id": 7,
    "nome": "Lorem ipsum Occaecat esse cillum deserunt reprehenderit",
    "img": "/images/img7.jpg"
}, {
    "id": 8,
    "nome": "Lorem ipsum Tempor dolor commodo fugiat elit in",
    "img": "/images/img8.jpg"
}, {
    "id": 9,
    "nome": "Lorem ipsum Ut mollit eu nostrud Duis",
    "img": "/images/img9.jpg"
}, {
    "id": 10,
    "nome": "Lorem ipsum Ut cillum in voluptate deserunt",
    "img": "/images/img10.jpg"
}];

Also use a <div> to receive all items:

...
<body>
    <div id="items-container"></div>
...

The iteration of JSON data can be done as follows:

var dados = JSON.parse('dados.json');

var container = document.getElementById('items-container'),
    divCard,
    divLogo,
    divLogoImg,
    divLogoH2,
    divLogoP;

for (var i in dados) {
    // Veja seu objeto para organizar as informações
    console.log(dados[i]);

    divLogoP = document.createElement('p');
    divLogoP.textContent = "Outro titulo";

    divLogoH2 = document.createElement('h2');
    divLogoH2.textContent = "title imagens";

    divLogoImg = document.createElement('img');
    divLogoImg.src = "/images/img10.jpg";

    divLogo = document.createElement('div');
    divLogo.className = "logo";
    divLogo.appendChild(divLogoImg);
    divLogo.appendChild(divLogoH2);
    divLogo.appendChild(divLogoP);

    divCard = document.createElement('div');
    divCard.className = "card";
    divCard.appendChild(divLogo);

    container.appendChild(divCard);
}

0

You can use the each to go through the json and insert the values in the fields you want example:

var json = {
    "resposta": [

      {
        "titulo": "A TERRA",
        "outroTitulo": "DIA DA TERRA"
      }
    ]

  } // exemplo de json

   $.each(json['resposta'], function(key, value) 
    {
        $.each(json['resposta'], function(key_result, value_result)
        {
           $('h2').append(value_result['titulo'] + '
'); $('h2').append(value_result['outroTitulo']); }); }); // each percorre todo json procurando pelos indices titulo e outroTitulo e substituem nas tags.

EXAMPLE

Browser other questions tagged

You are not signed in. Login or sign up in order to post.