How to return all content from a JSON?

Asked

Viewed 121 times

4

I have a JSON file in the following template:

[
  {
     "id": 1
      "nome": "José"
  },
  {
     "id": 2
      "nome": "João"
  }

]

And I’m making the following JSON server in PHP so that I get the entire JSON back. The way my code is it just returns each position 1 at a time

$path =  explode('/', $_GET['path']);
$contents = file_get_contents('tickets.json');

$json = json_decode($contents, true);

$method =  $_SERVER['REQUEST_METHOD'];

header('Content-type: application/json');
$body = file_get_contents('php://input');

if ($method === 'GET') {
    if ($json[$path[0]]) {
        echo json_encode($json[$path[0]]);
     }else{
         echo '[]';
     }
}

When I am the ?path=0 it returns me to position 0 with id 1 I wanted it to return everything inside the json if I put nothing in the path and if I put the ID in the path it returns me only 1

  • You want it to return all the values that are in the JSON file when you receive the value 0 in GET?

  • @Ismaelsilva I want that if I do not put anything it returns me all and if I put something in the example path the ID and it returns me only one

  • Your path variable, will it exist even without value? Example, "? path="

  • @Ismaelsilva Not necessarily, I just want a getAll if it doesn’t have a path or if it has a getById path

2 answers

1


Good afternoon!
See if this way helps you

<?php

$path = null;
/**
    Condicional para verificar se a variável $_GET['path'] existe,
    caso exista é inserido o valor nele
**/
if(isset($_GET['path'])) {
    $path = $_GET['path'];
}
$contents = file_get_contents('tickets.json');

$json = json_decode($contents, true);

$method =  $_SERVER['REQUEST_METHOD'];

header('Content-type: application/json');
$body = file_get_contents('php://input');

if ($method === 'GET') {
    /**
        verifica se é nula ou vazia ou se não inteiro (caso haja necessidade)
    **/
    if(is_null($path) || $path === '') {
        /**
            Retorna todos os dados do JSON
        **/
        echo json_encode($json);
    } else {
        if ($data = GetById($json, $path)) {
            echo json_encode($data);
        }else{
            echo '[]';
        }
    }
}

/**
    Fiz uma função para ficar mais organizado
**/
function GetById ($allData, $id) {
    $count = count($allData);
    /**
        Aqui é rodado um laço que verifica se o numero que venho na variável path é igual ao id do arquivo
    **/
    for ($i = 0; $i < $count; $i++) {
        if($allData[$i]['id'] == $id) {
            /**
                Aqui ele dá o retorno para não precisar percorrer todos os dados,
                isso vai ajudar no desempenho da aplicação, pois só irá percorrer todos os dados se for necessário 
            **/
            return $allData[$i];
        }
    }
    /**
        retorna nulo se não encontrar nada
    **/
    return null;
}
  • that method worked in parts but I was unable to do getbyid and ! is_int($path) I had to pull out to fall into Else

  • 1

    Okay, I’ll modify the code

-1

You can count the number of houses that contains the array and then have them printed in a loop.

See if this example helps you:

if ($method === 'GET') {
  if (count($json[$path]) == 1) {
    echo json_encode($json[$path[0]]);
  }
  else if(count($json[$path]) > 1) {
    $n = count($json[$path]);
    for($i=0;$i<$n;$i++)
    {
      echo json_encode($json[$path[$i]]);
    }
else{
         echo '[]';
     }
}

Browser other questions tagged

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