1

I have a simple array from a php file (the reason for not using a json file is cause this info comes from a mysql database)

$array[0] = array('id' => 1,'price' => '325');
$array[1] = array('id' => 2,'price' => '486');      
header('Content-type: application/json');
echo json_encode($array);

and it echos as:

[{"id":1,"price":"325"},{"id":2,"price":"486"}]

now what I want to do is take the id and add it to a variable called counterval so that JavaScript will read it as

counterval1 = 325;
counterval2 = 486;

but I can't seem to get it to read that way. Here is the script at the current moment.

$.getJSON('test.php',function(data) {
    $.each(data, function(i) {
    counterval + data[i].id = data[i].price;
    console.log (counterval2);
});
    $('#results').html(counterval2);    
});
var counterval1 = 0;
var counterval2 = 0;

any help on this would be greatly appreciated.

Keleko
  • 245
  • 4
  • 15

2 Answers2

3

you can't do that... but you can do this...

var counterval = [];

$.getJSON('test.php',function(data) {
    $.each(data, function(i) {
         counterval[data[i].id] = data[i].price;
         console.log (counterval[2]);
    });
    $('#results').html(counterval[2]);    
});
counterval[1] = 0;
counterval[2] = 0;
Reigel Gallarde
  • 64,198
  • 21
  • 121
  • 139
2

See my comment on your post. If you really want the vars to look like you explained:

eval("counterval" + data[i].id + " = data[i]..price");
alert(counterval1);
Imperative
  • 3,138
  • 2
  • 25
  • 40