开发者

iterate through json and access two dimensions deep

开发者 https://www.devze.com 2023-03-28 03:12 出处:网络
I\'m returning rows from a mysql database in php and then making an array of all these rows and then json encoding this.I am then trying to turn that json into autocomplete for jquery, not that relave

I'm returning rows from a mysql database in php and then making an array of all these rows and then json encoding this. I am then trying to turn that json into autocomplete for jquery, not that relavent. The issue I have is that once I have it in json, there is no defining the rows. How do I access the same json.id that is in every "r开发者_StackOverflow中文版ow" returned in json? here is a sample json object I'm using

      [{"id":"95833","fname":"john","lname":"walker","email":"john.walker@john.edu","major":"UNDECID  ED","year":"14","gender":"0","created":"0000-00-00 00:00:00"},        {"id":"95834","fname":"joseph","lname":"train","email":"jo.train@john.edu","major":"","year":"  12","gender":"0","created":"0000-00-00 00:00:00"}]

I do I access the first id, or the second one?, etc


Here's some sample code showing how to iterate over your data:

var data = [{"id":"95833","fname":"john","lname":"walker","email":"john.walker@john.edu","major":"UNDECID  ED","year":"14","gender":"0","created":"0000-00-00 00:00:00"},        {"id":"95834","fname":"joseph","lname":"train","email":"jo.train@john.edu","major":"","year":"  12","gender":"0","created":"0000-00-00 00:00:00"}];
for( var i = 0; i < data.length; i ++ )
{
    var item = data[i];
    var thisID = item.id;
    // do something clever here
}


jQuery will parse the JSON into a Javascript array of objects for you:

data[0].id // First id
data[1].id // Second id


I think, I think you're trying to access the "columns", not the rows. Incidentally, this general problem of the relation model of the a SQL database not matching the object model of most languages is called "The Impedance Mismatch", and it sucks. Your particular issue could be addressed (in jQuery) with:

$.map(data, function(n) { return n.id } );

Which will return an array containing all the id values.


If you are using jQuery 1.6 then it's very simple

// to get ['id', 'fname', 'lname', 'email', 'major', 'year', 'gender', 'created']
// you only need to map the first element of the data array and return the key.

var columnArray = $.map(data[0], function (val, k) {
    return k;
});

Happy Coding :)

0

精彩评论

暂无评论...
验证码 换一张
取 消