Work with JSON data in PHP

0

I have a variable JavaScript in the following way:

var datos ={Tabla: 'Principal' , CampoConsulta:['Nombre','Apellido_Pa','Apellido_Ma'], DatosConsulta:['Juan Luis','Perez','Martinez'], TipoDato:['s','s','s'], Val:[1,2,3] };

This data I want to pass to PHP to then create a query MySQL

Ajax

function busquedaFiltros(){
var data = stringify(datos);
$.ajax({
    url: '../../php/instancias.php',
    type: 'POST',
    data: {Funcion: 'Filtros', Datos: data},
})
.done(function(data) {
    $("#tbl_TblFil").empty();
    $("#tbl_TblFil").append(data);
})
.fail(function() {
    console.log("error");
})    

}

But already in PHP I no longer know how to work with JSON data. For example I have an array inside my object json and I would like to go through it. I have read several things, but they leave me with more questions than answers.

    
asked by Ferny Cortez 04.02.2018 в 03:44
source

1 answer

1

Using the json_decode method, you can achieve it. This what it does is that it converts the json into an object and thus you can access its properties as any object:

$datos = json_decode($_POST["DATOS"]);
echo $datos->Tabla

// para acceder a un array lo haces como lo harias con un objeto normal

foreach($datos->CampoConsulta as $campo)
{
  echo $campo;
}

As you may have noticed, to access the elements of the array $datos->CampoConsulta is used since that is the name of the property in the json and thus would be for the array DatosConsultas , TipoDato and Val . If the array contained objects instead of an array of string, then you would only have to access the properties of it:

foreach($datos->arrayConObjetos as $value)
{
  echo $value->nombrePropiedad;
}
    
answered by 04.02.2018 / 03:51
source