Create JSON object from PHP MySQL result - php

I want to create a JSON object from my MySQL results with PHP so I can pass it to JavaScript. I don't quite understand the difference between JSON array and JSON object.
This is how I do it. But is there a better way? This is the array way I believe?
$json = array();
while($r=mysql_fetch_array($res)){
$json['firstname'] = $r['firstname'];
$json['lastname'] = $r['lastname'];
}
echo json_encode($json);
I want to be able to get the info from JavaScript, by selecting all first names only If I wish etc..

you can try this, fetch data and push to array, then echo that array
$info=array();
while($row = mysql_fetch_array($res,MYSQL_ASSOC)){
array_push($info,$row);
}
echo json_encode($info);
would return
array(2) { [0]=> array(3) { ["id"]=> string(1) "1" ["firstname"]=> string(3) "foo" ["lastname"]=> string(3) "bar" } [1]=> array(3) { ["id"]=> string(1) "2" ["firstname"]=> string(3) "foo" ["lastname"]=> string(3) "bar" } }
json
[{"id":"1","firstname":"foo","lastname":"bar"},{"id":"2","firstname":"foo","lastname":"bar"}]

Well this would encode every row, with each row being the JSON Object:
$json = array();
while($r=mysql_fetch_array($res)){
$json[] = $r;
}
echo json_encode($json);

Related

Keep getting "Array" from fetching decoded JSON data?

When I encode the json data fetching from the mysql database, I get this:
[{"userid":"11","postid":"12"},{"userid":"13","postid":"12"},{"userid":"16","postid":"12"}]
And I am trying to get only the userid's like this: 11, 13, 16.
Decoding the json data gives me an output of: Array. And nothing else. When I var_dump this is my results:
array(3) {
[0]=> array(2) {
["userid"]=> string(2) "11"
["postid"]=> string(2) "12"
}
[1]=> array(2) {
["userid"]=> string(2) "13"
["postid"]=> string(2) "12"
}
[2]=> array(2) {
["userid"]=> string(2) "16"
["postid"]=> string(2) "12"
}
So I know there is data present, it's just not showing for some reason.
Here is what my query looks like:
if(isset($_POST['postuserid'])){
$uid = $_POST['postuserid'];
$ssql = "SELECT * FROM foodid WHERE postid=$uid";
$rresult = mysqli_query($db,$ssql);
while ($lrow = mysqli_fetch_assoc($rresult)){
$ret[] = $lrow;
$postjson = json_encode($ret);
$decode_postid = json_decode($postjson, true);
$new_postid = $decode_postid;
}
var_dump($new_postid);
die($new_postid);
// die($new_postid['userid']); is what I need along with all data userid fetched.
}
Is there a reason why this works when I encode json data, but not when I decode the json data?
Are you trying to get that array out of the die function? It can only take a string or int.
http://php.net/manual/en/function.exit.php
Your array is there... just do something like:
$ids = '';
foreach ($new_postid as $post) {
$ids .= $post['userid'] . ',';
}
$ids = rtrim($ids,',');
die($ids);
Try mapping those results:
$new_postid = $decode_postid;
$new_postid = array_map(function($item){
return $item['userid'];
}, $new_postid);
var_dump($new_postid);
Output
array(3) {
[0]=>
string(2) "11"
1=>
string(2) "13"
[2]=>
string(2) "16"
}
If you need to output as string, just use implode function
die(implode(',',$new_postid));
http://php.net/manual/en/function.array-map.php

How to access JSON decoded array in PHP

I returned an array of JSON data type from javascript to PHP, I used json_decode($data, true) to convert it to an associative array, but when I try to use it using the associative index, I get the error "Undefined index" The returned data looks like this
array(14) { [0]=> array(4) { ["id"]=> string(3) "597" ["c_name"]=> string(4) "John" ["next_of_kin"]=> string(10) "5874594793" ["seat_no"]=> string(1) "4" }
[1]=> array(4) { ["id"]=> string(3) "599" ["c_name"]=> string(6) "George" ["next_of_kin"]=> string(7) "6544539" ["seat_no"]=> string(1) "2" }
[2]=> array(4) { ["id"]=> string(3) "601" ["c_name"]=> string(5) "Emeka" ["next_of_kin"]=> string(10) "5457394839" ["seat_no"]=> string(1) "9" }
[3]=> array(4) { ["id"]=> string(3) "603" ["c_name"]=> string(8) "Chijioke" ["next_of_kin"]=> string(9) "653487309" ["seat_no"]=> string(1) "1" }
Please, how do I access such array in PHP? Thanks for any suggestion.
As you're passing true as the second parameter to json_decode, in the above example you can retrieve data doing something similar to:
$myArray = json_decode($data, true);
echo $myArray[0]['id']; // Fetches the first ID
echo $myArray[0]['c_name']; // Fetches the first c_name
// ...
echo $myArray[2]['id']; // Fetches the third ID
// etc..
If you do NOT pass true as the second parameter to json_decode it would instead return it as an object:
echo $myArray[0]->id;
$data = json_decode($json, true);
echo $data[0]["c_name"]; // "John"
$data = json_decode($json);
echo $data[0]->c_name; // "John"
$data = json_decode(...);
$firstId = $data[0]["id"];
$secondSeatNo = $data[1]["seat_no"];
Just like this :)
As you're passing true as the second parameter to json_decode, in the above example you can retrieve data doing something similar to:
<?php
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json));
var_dump(json_decode($json, true));
?>
This may help you!
$latlng='{"lat":29.5345741,"lng":75.0342196}';
$latlng=json_decode($latlng,TRUE); // array
echo "Lat=".$latlng['lat'];
echo '<br/>';
echo "Lng=".$latlng['lng'];
echo '<br/>';
$latlng2='{"lat":29.5345741,"lng":75.0342196}';
$latlng2=json_decode($latlng2); // object
echo "Lat=".$latlng2->lat;
echo '<br/>';
echo "Lng=".$latlng2->lng;
echo '<br/>';
When you want to loop into a multiple dimensions array, you can use foreach like this:
foreach($data as $users){
foreach($users as $user){
echo $user['id'].' '.$user['c_name'].' '.$user['seat_no'].'<br/>';
}
}

PHP: Foreach an array won't output

When I dump the variable it has a data:
var_dump($result);
object(stdClass)#2 (5) { ["user_id"]=> string(1) "1" ["username"]=> string(6) "user_name" ["email"]=> string(14) "test#mail.com" ["password"]=> string(32) "password" ["test"]=> string(1) "1" }
But when I use foreach no value has return except if I just echo $data; but I want to be specific to the value I want to get.
foreach($result as $data){
echo $data->use_id;
echo $data->username;
}
Why there is no returned value?
Try this : json_decode converts json string to array. Ref: http://php.net/manual/en/function.json-decode.php
$array = json_decode($result, true);
echo "<pre>";
print_r($array);
You can use foreach to $array and echo the result.
You don't need to iterate over the object. Just do this.
echo $result->user_id;
echo $result->username;
With the sample you provided you are treating each property in $result as an object and looking for user_id and user_name (which don't exist).
As you wrote:
var_dump($result);
object(stdClass)#2 (5) { ["user_id"]=> string(1) "1" ["username"]=> string(6) "user_name" ["email"]=> string(14) "test#mail.com" ["password"]=> string(32) "password" ["test"]=> string(1) "1" }
So the result is an object itself. so if you want specify and fetch exact variable, there's no need to iterate it!

2D arrays in JSON getting converted into a 1D array of objects

I've looked around but haven't found an answer so I figured i would give it an ask myself.
I've noticed that a round trip to JSON converts a 2-D array into a 1D array of Objects.
Is there any way around this or should I just try to work with objects from the beginning (e.g. $test->1->4 ? see example below
$test = array();
$test[0][0] = "0-0";
$test[0][2] = "0-2";
$test[1][1] = "1-1";
$test[1][2] = "1-2";
var_dump($test);
$encoded = json_encode($test);
var_dump($encoded);
$recreated = json_decode($encoded);
var_dump($recreated);
outputs
array(2) {
[0]=>
array(2) {
[0]=>
string(3) "0-0"
[2]=>
string(3) "0-2"
}
[1]=>
array(2) {
[1]=>
string(3) "1-1"
[2]=>
string(3) "1-2"
}
}
string(45) "[{"0":"0-0","2":"0-2"},{"1":"1-1","2":"1-2"}]"
array(2) {
[0]=>
object(stdClass)#19 (2) {
["0"]=>
string(3) "0-0"
["2"]=>
string(3) "0-2"
}
[1]=>
object(stdClass)#20 (2) {
["1"]=>
string(3) "1-1"
["2"]=>
string(3) "1-2"
}
}
This is because you don't have ongoing indexes in your array:
$test = array();
$test[0][0] = "0-0";
$test[0][2] = "0-2";
In this case json_encode() HAS to create an object because there is a numeric key (1) missing.
You can decode it back to an array with json_decode($txt, true), but this is only a work around, not a fix.
By default json_decode will convert the json into objects. You code needs to look like:
$recreated = json_decode($encoded, true);
You can decode as arrays:
$recreated = json_decode($encoded, true);

I have two values in an array when i execute the stored Procedure in php But iam returned wih one array value

$result = $mysql->callSP('STOREDPE1',$in);
$arr_tmp=array();
foreach ($result['record'] as $rows) {
echo "one value";
if(!empty($rows)){
echo "Two Value";
$arr_tmp[$rows['field1']] = $rows['field2'];
}
}
return $arr_tmp;
When I say var_dump($result) it has two values in array. But when I Execute arr_tmp it is returned with one value.
out put of ``var_dump($result)`
["param"]=>
array(4) {
["whcode"]=>
string(5) "001"
["mode"]=>
string(1) "A"
["stock_type"]=>
string(4) "AAA"
["process_name"]=>
string(7) "AAAA"
}
["record"]=>
array(2) {
[0]=>
array(3) {
["Field1"]=>
string(5) "value1"
["Field2"]=>
string(1) "CCC"
["Field3"]=>
string(4) "BCC"
}
[1]=>
[0]=>
array(3) {
["Field1"]=>
string(5) "value1"
["Field2"]=>
string(1) "CCC"
["Field3"]=>
string(4) "BCC"
}
}
}
output of var_dump (arr_tmp)
[1]=>
[0]=>
array(3) {
["Field1"]=>
string(5) "value1"
["Field2"]=>
string(1) "CCC"
["Field3"]=>
string(4) "BCC"
}
Both the array values seems to be same
I have the values overwriting in the array
Very hard to understand and read with the bad formatting, please take care to post it with proper formatting.
I think the answer is this:
$result = $mysql->callSP('STOREDPE1',$in);
$arr_tmp=array();
foreach ($result['record'] as $rows) {
echo "one value";
if(!empty($rows)){
echo "Two Value";
$arr_tmp[][$rows['field1']] = $rows['field2'];
}
}
var_dump($arr_tmp);
That should store both sets of data, you just needed to make it a multi-dimensional array. That is, if that is your question and I did not mis-read it through that garbled text above.
Update
This option is not recommended better to learn how to use arrays, simply posted for an example of usage:
$result = $mysql->callSP('STOREDPE1',$in);
$arr_tmp=array();
$i=0;
foreach ($result['record'] as $rows) {
echo "one value";
if(!empty($rows)){
echo "Two Value";
$arr_tmp[][$rows['field1'] . "_$i"] = $rows['field2'];
}
$i++;
}
var_dump($arr_tmp);

Categories