I'm trying to make sense of the JSON output and I was hoping someone here might be kind enough to walk me through it as it's been a while since I used JSON.
I have the following PHP
$Query01 = "SELECT `Department`,`DepartmentHeadID` FROM `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 the 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 I was expecting was the column Department
& DepartmentHeadID
Would really appreciate understanding this output a little more.
Any thoughts...?
You actually missed that part in the documentation of array mysql_fetch_array ( resource $result [, int $result_type = MYSQL_BOTH ] )
result_type
The type of array that is to be fetched. It's a constant and can take the following values: MYSQL_ASSOC, MYSQL_NUM, and MYSQL_BOTH.
The type of returned array depends on how result_type is defined. By using MYSQL_BOTH (default), you'll get an array with both associative and number indices.
source : http://php.net/manual/en/function.mysql-fetch-array.php
Since MYSQL_BOTH
is the default value for $result_type
when you do not pass the second parameter to mysql_fetch_array
, you end up with both the number and associative indices in your array.
So if you only want Department
& DepartmentHeadID
, you should go by
$r = mysql_fetch_array($Result01, MYSQL_ASSOC)
Using MYSQL_ASSOC, you only get associative indices (as mysql_fetch_assoc() works)
Bottom line : I would also recommend to prepare yourself to the deprecation of mysql_*
functions as you can clearly see it stated in the official documentation linked here above and that you get information about PDO
A good starting point may be this question : Why shouldn't I use mysql_* functions in PHP?