json_encode returning empty

Asked

Viewed 455 times

1

I am performing a basic query in the bank, using the following code:

public function searchAllProducts(){
    $array = array();
    $select = $this->connection->prepare("Select * from tb_produto");
    $select->setFetchMode(PDO::FETCH_ASSOC);
    $select->execute();
    $produtos = $select->fetchAll();

    foreach ($produtos as $produto) {
      $product = new Produto($produto['IDProduto'], $produto['NomeProduto'], $produto['PrecoProduto'], $produto['DTValProduto'], $produto['QtdProduto'], $produto['DescricaoProduto']);
      array_push($array, $product);
    }
    return $array;
  }

The problem is that when I transform the array into json, using the json_encode, in this way:

require_once '../connection.php';
require_once '../class/ProdutoDAO.php';

$dao = new ProdutoDAO($connection);
$produtos = $dao->searchAllProducts();
//var_dump($produtos);

$json = json_encode($produtos);

echo $json; 

This returns to me [{},{}].

OBS: The array is filled, when I give one var_dump($produtos), is shown the products as expected.

  • Produto() is a class with private attributes and gets to access them?

  • Place what you have inside the return array

1 answer

3


This happens because you are trying to turn your object into Json format, json_encode will only work by default on primitive types and fields public of objects.

For json_encode to work, implement the interface JsonSerializable, method jsonSerialize, and this is what you need to do for your Product object produce some output without transforming all properties into public.

Example

class Fruit implements JsonSerializable {
    public
        $type = 'Apple',
        $lastEaten = null;

    public function __construct() {
        $this->lastEaten = new DateTime();
    }

    public function jsonSerialize() {
        return [
            'type' => $this->type,
            'lastEaten' => $this->lastEaten->format(DateTime::ISO8601)
        ];
    }
}
echo json_encode(new Fruit()); //which outputs: {"type":"Apple","lastEaten":"2013-01-31T11:17:07-0500"}

More information

  • Thanks ! (there should be a gson for php :/)

  • See if this helps: https://github.com/tebru/gson-php

  • Thanks again !

Browser other questions tagged

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