Browse JSON in PHP

3

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;
     }
     ?>
    
asked by Niel Jobs 04.07.2018 в 09:17
source

3 answers

4

The problem you are having is that you do not directly receive a JSON value, but rather that you receive a JSON encoded string:

<?php
$_POST['datos'] = '"{\"numeros\":{\"19\":1,\"8\":1,\"30\":1,\"31\":1,\"35\":1,\"45\":1}}"';
$resultado = json_decode($_POST['datos']);
echo 'Resultado vale: ', $resultado, PHP_EOL;
foreach ($resultado->numeros as $key => $value) {
  echo "$key => $value", PHP_EOL;
}

The result of the execution is:

Resultado vale: {"numeros":{"19":1,"8":1,"30":1,"31":1,"35":1,"45":1}}
PHP Notice:  Trying to get property 'numeros' of non-object in /tmp/pr.php on line 5
PHP Warning:  Invalid argument supplied for foreach() in /tmp/pr.php on line 5

As you can see, $resultado is worth (as you put in your question) {"numeros":{"19":1,"8":1,"30":1,"31":1,"35":1,"45":1}} , but as a string, not as a JSON value, so trying to access the property numeros of a string sends you the message of warning Trying to get property 'numbers' of non-object .

So the problem seems to be in origin (where you mount the string to send to PHP).

One solution (without modifying the origin of the data) could be:

<?php
$_POST['datos'] = '"{\"numeros\":{\"19\":1,\"8\":1,\"30\":1,\"31\":1,\"35\":1,\"45\":1}}"';
$resultado = json_decode($_POST['datos']);
echo 'Resultado vale: ', $resultado, PHP_EOL;
/* Ahora decodificamos la cadena decodificada anteriormente */
$resultado = json_decode($resultado);
foreach ($resultado->numeros as $key => $value) {
  echo "$key => $value", PHP_EOL;
}

Whose result is:

Resultado vale: {"numeros":{"19":1,"8":1,"30":1,"31":1,"35":1,"45":1}}
19 => 1
8 => 1
30 => 1
31 => 1
35 => 1
45 => 1

Although decoding twice the JSON obtained solves your problem, you should correct it at source (in the javascript code that sends the data).

    
answered by 04.07.2018 / 10:10
source
2

You can put the second argument from json_decode to true and get an associative array with which to work, avoiding encountering object problems.

$datos = '{"numeros":{"19":1,"8":1,"30":1,"31":1,"35":1,"45":1}}';

$resultado=json_decode($datos,true);

foreach($resultado['numeros'] as $k => $v)
{
    echo $k; // Esto devuelve las variables por separado

    echo $v;
}
    
answered by 04.07.2018 в 09:55
1

The matter is simpler friends.

It's about reading the array in PHP, right?

Well, it turns out that ¡ $_POST is just that, an array! .

So if you want to read what's in $_POST["datos"] , read it as such, you do not have to convert it to JSON.

Try this and you'll see:

$arrDatos=$_POST["datos"];
foreach ($arrDatos as $k=>$v){
    echo "key: $k - value: $v".PHP_EOL;
}

For more tests, do this:

print_r($_POST);

You'll see that $_POST is nothing other than an array .

The only case in which what you are trying to make sense of is if your variable $_POST would show like this with:

var_dump($_POST);
array(1) {
  ["datos"]=>
  string(54) "{"numeros":{"19":1,"8":1,"30":1,"31":1,"35":1,"45":1}}"
}

In that case, you would have to access the key datos of your array $_POST , and convert the value of that key, which is only a string (note that the var_dump says string(54) ), in JSON, passing the parameter TRUE to create an array for PHP, something like this: $arrDatos=json_decode($_POST["datos"],TRUE);

In that case, $arrDatos will have this structure, you can see it if you make a var_dump($arrDatos); :

array(1) {
  ["numeros"]=>
  array(6) {
    [19]=>
    int(1)
    [8]=>
    int(1)
    [30]=>
    int(1)
    [31]=>
    int(1)
    [35]=>
    int(1)
    [45]=>
    int(1)
  }

Then you can read the key numeros of that array in a foreach .

The complete code would then be this:

$arrDatos=json_decode($_POST["datos"],TRUE);

foreach ($arrDatos["numeros"] as $k=>$v){
    echo "key: $k  \t/\t value: $v".PHP_EOL;
}

The output would be:

key: 19     /    value: 1
key: 8      /    value: 1
key: 30     /    value: 1
key: 31     /    value: 1
key: 35     /    value: 1
key: 45     /    value: 1
    
answered by 04.07.2018 в 12:09