On 4 Sep 2012, at 7:04 AM, Hassan Alnatour <[email protected]> wrote:
> I am trying to use a data table called jtable , it uses arrays and return it
> as json .. now i have the php code for it :
>
> //Get records from database
> $result = mysql_query("SELECT * FROM people;");
>
> //Add all records to an array
> $rows = array();
> while($row = mysql_fetch_array($result))
> {
> $rows[] = $row;
> }
>
> //Return result to jTable
> $jTableResult = array();
> $jTableResult['Result'] = "OK";
> $jTableResult['Records'] = $rows;
> print json_encode($jTableResult);
>
> and it
> returns :
>
>
> {
> "Result":"OK", "Records":[
> {"PersonId":1,"Name":"Benjamin
> Button","Age":17,"RecordDate":"\/Date(1320259705710)\/"},
> {"PersonId":2,"Name":"Douglas
> Adams","Age":42,"RecordDate":"\/Date(1320259705710)\/"},
> {"PersonId":3,"Name":"Isaac
> Asimov","Age":26,"RecordDate":"\/Date(1320259705710)\/"},
> {"PersonId":4,"Name":"Thomas
> More","Age":65,"RecordDate":"\/Date(1320259705710)\/"}
> ]
> }
> now i did it in web2py like this :
> def person():
> data = db().select(db.Person.ALL)
> mylist = {}
> mylist['Result'] = 'OK'
> mylist['Records']=[]
> for i in data:
> i.name = {'ID':i.id,'Name': i.name,'Age': i.age}
> mylist['Records'].append(i.name)
> return mylist
>
> but there is still something wrong in the way i create the array , and its
> making some problems for me in the edit/delete .. so is the function i did is
> the same as the php code up there ..
> best regards,
It would be helpful to know what "something wrong" and "some problems" mean.
FWIW, I'd recode at least this much:
def person():
data = db().select(db.Person.ALL)
mydict = dict(Result='OK', Records=[])
for i in data:
mydict['Records'].append(dict(ID=i.id, Name=i.name, Age=i.age))
return mydict
Part of my changes are only stylistic (I don't like naming a dict 'mylist'),
and my version is more concise. But substantively, I'd be suspicious of
assigning i.name to a dict containing a reference to i.name, not to mention
that using a local variable is more efficient here.
--