I have a problem that I can not solve, I am still a novice in this. I receive in a php file the following JSON that I decode in this way.
$resultado=json_decode($_POST["datos"]);
and when I show the result variable it throws me down.
{"numeros":{"19":1,"8":1,"30":1,"31":1,"35":1,"45":1}}
What I do not achieve is to be able to read it to get the values it has inside. Try in many ways and I could not, the most common mistake that I get is this "Trying to get property of non-object".
I tried to traverse it with foreach
, putting it in an array but I can not do it.
This is one of the ways I try.
foreach ($resultado->numeros as $key => $value) {
echo $key;
echo $value;
}
What I'm looking for is to be able to show the key for example 19 and its respective value in that case 1.
I edit my question to add the origin of the data.
This is the whole code path.
$('#btn_buscar').on('click', function(){
$.ajax({
type: "POST",
url: 'procesos/estadisticas_jugadas.php',
data: $("#frm_buscar").serialize(),
success: function(data)
{
//alert(data);
cargar_estadisticas(data);
}
});
return false;
});
function cargar_estadisticas(data){
var estadisticas = JSON.stringify(data);
$.ajax({
type: 'POST',
url: 'procesos/tabla_estadisticas.php',
data: "datos=" + estadisticas,
success: function (data) {
alert(data);
},
error: function(){
alert('Error');
}
});
}
The Query that gives me the numbers is in the following PHP called estadisticas_jugada.php
.
The query I keep in $sql
I do not put it because it's too long but it works well if necessary I edit it again and add it.
$resultado = mysqli_query($mysqli,$sql);
if(!$resultado)
die("Error");
else{
$numeros = array();
$data = array();
while($registronumeros=$resultado->fetch_array(MYSQLI_BOTH))
{
$numeros[$registronumeros["Numeros"]]++;
}
$data['numeros'] = $numeros;
echo json_encode($data);
}
mysqli_free_result($resultado);
mysqli_close($mysqli);
?>
This is the file where the error was generated. or subo corrected and working with that double decoding, I'm trying to see where part of the origin is saved as string json so avoid double decoding.
The file is named tabla_estadisticas.php
.
<?php
require_once 'conexion.php';
$data=json_decode($_POST["datos"]);
echo 'Resultado vale: ', $data, PHP_EOL;
$resultado = json_decode($data);
foreach ($resultado->numeros as $key => $value) {
echo "$key => $value", PHP_EOL;
}
?>