Create an array of JSON objects with PHP

0

I have 3 classes in PHP which I use to extract information from a database with which I would like to print or return an array with json objects from all the states and their respective countries so that it will be somewhat similar to the following:

[
    {
        "id": 1,
        "nombre": "Coahuila",
        "pais":
        {
            "id": 1,
            "nombre": "México"
        }
    },
    {
        "id": 2,
        "nombre": "Durango",
        "pais":
        {
            "id": 1,
            "nombre": "México"
        }
    }
]

Taking into account the following classes.

Class for the connection to MySQL     

    class Conexion {
    private static $conexion;
        private static $server = "mysql:host=localhost;dbname=prueba";
        private static $user = "root";
        private static $pass = "";

        public static function conectar() {
        try {
        self::$conexion = new PDO(self::$server, self::$user, self::$pass);
                self::$conexion->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            }
            catch(PDOException $e) {
                $e->getMessage();
            }
        }

        public static function desconectar() {
            try {
                self::$conexion = NULL;
            }
            catch(PDOException $e) {
                $e->getMessage();
            }
        }

        public static function seleccionar(string $query, array $array = NULL) : PDOStatement {
        try {
                self::conectar();
                $sth = self::$conexion->prepare($query, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
                $sth->execute($array);
                return $sth;
            }
            catch(PDOException $e){
                $e->getMessage();
                return $sth = NULL;
            }
            finally {
                self::desconectar();
            }
        }
    }
?>

Class to create objects Country     

    class Pais {

        //Atributos
        private $id;
        private $nombre;

        //Constructores
        public function __construct(){
            $this->id = 0;
            $this->nombre = "";
        }

        public function __destruct() {}

        public function getId() : int {
            return $this->id;
        }

        public function getNombre() : string {
            return $this->nombre;
        }

        public function setId(int $id) {
            $this->id = $id;
        }

        public function setNombre(string $nombre){
            $this->nombre = $nombre;
        }

        //Seleccion de varios objetos
        private static function objetos(string $query, array $array = NULL) : array {
            $sth = Conexion::seleccionar($query, $array);
            if($sth->rowCount() > 0) {
                while($r = $sth->fetchObject()) {
                    $pais = new Pais();
                    if(!is_null($r->id_pais))
                        $pais->setId((int)$r->id_pais);
                    if(!is_null($r->nombre_pais))
                        $pais->setNombre($r->nombre_pais);
                    $datos[] = $pais;
                }
                return $datos;
            }
            else {
                return $datos = NULL;
            }
        }
        public static function todos() : array {
            $query = "SELECT * FROM paises;";
            return Pais::objetos($query);
        }
    }
?>

Class to create objects State     

    class Estado {

        //Atributos
        private $id;
        private $nombre;
        private $pais;

        //Constructor
        public function __construct() {
            $this->id = 0;
            $this->nombre = "";
            $this->pais = new Pais();
        }
        //Destructor
        public function __destruct() {}

        //Propiedades
        public function getId():int {
            return $this->id;
        }
        public function setId(int $id){
            $this->id = $id;
        }
        public function getNombre():string {
            return $this->nombre;
        }
        public function setNombre(string $nombre) {
            $this->nombre = $nombre;
        }
        public function getPais():Pais {
            return $this->pais;
        }
        public function setPais(Pais $pais) {
            $this->pais = $pais;
        }

        //Seleccion y guarda paises en un arreglo
        private static function objetos(string $query, array $array = NULL) : array {

            //Obtiene una sentencia que fue preparada y ejecutada en la clase conexion.php
            $sth = Conexion::seleccionar($query, $array);

            if($sth->rowCount() > 0) {
                while($r = $sth->fetchObject()) {
                    $estado = new Estado();
                    if(!is_null($r->id_estado))
                        $estado->setId((int)$r->id_estado);
                    if(!is_null($r->nombre_estado))
                        $estado->setNombre($r->nombre_estado);
                    if(!is_null($r->pais_estado))
                        $estado->setPais(Pais::porId((int)$r->pais_estado)); //Retorna una instancia de la clase Pais con sus atributos
                    $datos[] = $estado;
                }
                return $datos;
            }
            else {
                return $datos = NULL;
            }
        }

        public static function todos() : array {
            $query = "SELECT * FROM estados;";
            return Estado::objetos($query);
        }
    }
?>

Greetings

    
asked by Alejandro Arelis 22.05.2018 в 07:46
source

1 answer

1

You can use the JsonSerializable interface which allows you to convert an object to json once it is serialized.

How does it work?

You will have to implement it in your classes, for example

<?php    

use JsonSerializable

class Estado implements JsonSerializable {
    public function jsonSerialize()
    {
        return ['id' => $this->getId(), 'nombre' => $this->getNombre()];
    }
}

To serialize then just make a json enconde of the object. Example

print json_encode(new Estado, true)

I should print a json something like that

{
   'id': 1,
   'nombre': "Capital"
}

I hope this helps you:)

    
answered by 22.05.2018 в 15:39