Understanding a PHP Generated JSON Array -
i'm trying make sense of json output , hoping here might kind enough walk me through it's been while since used json.
i have following php
$query01 = "select `department`,`departmentheadid` `department`"; $result01 = mysql_query($query01) or die("error 01: " . mysql_error()); while($r = mysql_fetch_array($result01)) { // create json data: $rows[] = $r; } // echo json_encode($rows); $data = json_encode($rows); echo '<pre>'; print_r(json_decode($data)); echo '</pre>';
which generates following:
array ( [0] => stdclass object ( [0] => despatch [department] => despatch [1] => 1 [departmentheadid] => 1 ) [1] => stdclass object ( [0] => factory [department] => factory [1] => 2 [departmentheadid] => 2 ) [2] => stdclass object ( [0] => finishing [department] => finishing [1] => 3 [departmentheadid] => 3 ) [3] => stdclass object ( [0] => accounts [department] => accounts [1] => 8 [departmentheadid] => 8 ) [4] => stdclass object ( [0] => reps [department] => reps [1] => 13 [departmentheadid] => 13 )
all expecting column department
& departmentheadid
would appreciate understanding output little more.
any thoughts...?
you missed part in documentation of array mysql_fetch_array ( resource $result [, int $result_type = mysql_both ] )
result_type
the type of array fetched. it's constant , can take following values: mysql_assoc, mysql_num, , mysql_both.
type of returned array depends on how result_type defined. using mysql_both (default), you'll array both associative , number indices.
source : http://php.net/manual/en/function.mysql-fetch-array.php
since mysql_both
default value $result_type
when not pass second parameter mysql_fetch_array
, end both number , associative indices in array.
if want department
& departmentheadid
, should go
$r = mysql_fetch_array($result01, mysql_assoc)
using mysql_assoc, associative indices (as mysql_fetch_assoc() works)
bottom line : recommend prepare deprecation of mysql_*
functions can see stated in official documentation linked here above , information pdo
starting point may question : why shouldn't use mysql_* functions in php?
Comments
Post a Comment