traversing json from php

2

I build my json from php

        $marcas   = $this->MainModel->getmarcas();  
        $valores = array();
        foreach ($marcas as $value) {
            $Where["id_marca"] = $value->id_marca;
            $valores[] = $this->MainModel->getvalores($Where);
        }

        $this->output
                    ->set_content_type('application/json')
                    ->set_output(
                        json_encode(array(
                            'success'=>true,
                            'valores'=>$valores
                        ))  
        );

Staying this way:

  

I think it may be because I have a [] that is the use to insert   the foreach data

{
  "success": true,
  "valores": [
    [
      {
        "valor1": "1231",
        "valor2": "345"
      },
      {
        "valor1": "45345",
        "valor2": "435"
      },
      {
        "valor1": "4535",
        "valor2": "34"
      }
    ]
  ]
}

I tried to do it this way without results:

var valores = {
  "success": true,
  "series": [
    [
      {
        "valor1": "1231",
        "valor2": "345"
      },
      {
        "valor1": "45345",
        "valor2": "435"
      },
      {
        "valor1": "4535",
        "valor2": "34"
      }
    ]
  ]
};

$.each(valores, function(index, element) {
    console.log(element[index].valor1); 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
asked by Javier Antonio Aguayo Aguilar 10.08.2018 в 17:02
source

3 answers

0

In your JSON, valores is an array that contains another array that in turn contains the pairs {value1, value2}. Try going through it like this:

// Esto hace la iteración sobre el array "exterior"
$.each(valores, function(i, eli){ 
    // Esto itera sobre el array "interior"
    $.each(eli, function(j, elj){ 
        alert(elj.valor1); 
    }); 
});
    
answered by 10.08.2018 / 17:17
source
0

The problem is because your variable values is a plain text in json format, which to be able to run from javascript , you must use parseJSON in case you are implementing jquery .

To implement it, it would be as follows:

var json = jQuery.parseJSON( valores);
 $.each(json.valores, function(index, element) {
     alert(element.valor1); 
 });
    
answered by 10.08.2018 в 17:14
-2

Try a simple for as follows:

for(var i in data.valores.items) {
    console.log("Valor 1: "data.valores.items[i].valor1 +" Valor2: "+data.valores.items[i].valor1);  
}
    
answered by 10.08.2018 в 17:12