i want return my data from mysql to json array with do while loop.
when i return one record with json it is well. but i want return list of array in one json array.
how can do that with index in while? my code have error and i don't know how can do it. with one record it is well but more can't.
$json="array(";
do{
$json=."'$row_query['id']'=>array('fname'=>$row_query['fname'],'lname'=>$row_query['lname']),";
} while ($row_query = mysqli_fetch_assoc($query));
json=.")";
echo json_encode($json,JSON_UNESCAPED_UNICODE);
There's no need to add quotes, brackets, parentheses or whatever. json_encode function will do it for you. Just provide an array to it:
$json = [];
while ($row_query = mysqli_fetch_assoc($query)) {
$json[$row_query['id']] = [
'fname'=>$row_query['fname'],
'lname'=>$row_query['lname'],
];
}
echo json_encode($json,JSON_UNESCAPED_UNICODE);
This is the most super easy version. You may try this.
$json = new array();
do{
array_push($json,$row_query);
} while ($row_query = mysqli_fetch_assoc($query));
or
$json = [];
do{
$json[] = $row_query;
} while ($row_query = mysqli_fetch_assoc($query));
Atlast encode your json variable.
$json = json_encode($json);
echo $json;
Related
I read user from the database but I return json to ajax only return the last user because I cant concatenate the json encode.
$myObj = new \stdClass();
while ($fila = $bd->fila()) {
$myObj->NOMBRE = $fila["NOMBRE"];
$myObj->ROLENAME = $fila["ROLENAME"];
$myObj->IDUSER = $fila["IDUSER"];
$myJSON = json_encode($myObj);
}
echo $myJSON;
You are now overwriting $myJson in each iteration. We can also not "concatanate" two jsons (well, we could, but we shouldn't, cause it's laborious..).
Better put everything in one array/object and json_encode() at the very end.
$myObj = new \stdClass();
$users = array(); // instantiate a new array
while ($fila = $bd->fila()) {
$myObj->NOMBRE = $fila["NOMBRE"];
$myObj->ROLENAME = $fila["ROLENAME"];
$myObj->IDUSER = $fila["IDUSER"];
// add objects to that array
$users[] = $myObj;
}
// then at the end encode the whole thing to json:
echo json_encode($users);
Now here are some variants:
If you want everything that your db is returning in this items you could shorten that to:
$users = array(); // instantiate a new array
while ($fila = $bd->fila()) {
// add the whole item (cast as Object) to that array
$users[] = (Object) $fila;
}
// then at the end encode the whole thing to json:
echo json_encode($users);
If you don't care if the items are objects or arrays you could skip the casting and just add the array to the big array:
$users[] = $fila;
Maybe if you concatenate it as array like this
$myJSON[] = $myObj;
and then after the while
echo json_encode($myJSON);
You just have to collect data to big array and then encode whole array. Also there's no reason for creating new StdObjects instead of usual arrays.
// define empty array
$result = [];
while ($fila = $bd->fila()) {
// add to the array all needed elements one by one
$result[] = [
'NOMBRE' => $fila["NOMBRE"],
'ROLENAME' => $fila["ROLENAME"],
'IDUSER' => $fila["IDUSER"],
];
}
// encode whole result
echo json_encode($result);
I have this array
$data = [ 'admin'=>'1', 'natasha'=>'2', 'demo3'=>'3' ];
When I output it echo json_encode($data); I get {"admin":"1","natasha":"2","demo3":"3"} and this how I need it and it works well!
Now I'm trying to loop data from database like this:
$data = array();
foreach(TopicModel::theListofUsers($topic_cat,30) as $row) {
$data[]= array($row->user_name=>$row->user_id);
}
header('Content-Type: application/json');
echo json_encode($data);
But I'm getting this format [{"demo4":"4"},{"demo3":"3"}] but I need {"admin":"1","natasha":"2","demo3":"3"}
I tried many things, pass strings and convert to array or manipulate array but none of it gave me the proper format. Any idea?
$data = array();
foreach(TopicModel::theListofUsers($topic_cat,30) as $row) {
$data[$row->user_name] = $row->user_id;
}
header('Content-Type: application/json');
echo json_encode($data);
To achieve what you want, you need to set the name as the array key inside your foreach loop:
$data = array();
foreach(TopicModel::theListofUsers($topic_cat,30) as $row)
{
$data[$row->user_name]= $row->user_id;
}
header('Content-Type: application/json');
echo json_encode($data);
And I suggest that you escape both key and value of your array to avoid unwanted characters, otherwise your json_encode will fail returning false.
A simply way to do it can be: str_replace("'", "", $row->user_name) and str_replace("'", "", $row->user_id).
Can anyone explain me how to get the final value assigned to variable after completing executing while loop?
In my below code I wanted to echo the response out of while loop after fetching all the values from the rows.
Because if I put echo out of while loop it only shows 1st record.
while ($row = oci_fetch_array($array)) {
$response = $row['0']->load();
echo $response;
}
You will get the last rows value into the $response.
Cause: Every time the loop executes will assign value into the variable. But as you echo it you can see all the values as output.
So what you really need to do is storing the values in an array...
$response = array();
while ($row = oci_fetch_array($array)) {
$response[] = $row['0']->load();
}
print_r($response);
If you need further information about this , just let me know.
Since you are doing variable assignment and echo inside while loop, it will not serve your purpose.
You have to do it like below:-
$response = array(); // create an array
while ($row = oci_fetch_array($array)) {
$response[] = $row['0']->load(); // assign each value to array
}
echo "<pre/>";print_r($response);// print the array
Note:- this array will have all the values now. You can manipulate it in your desired way.Thanks
while ($row = oci_fetch_array($array)) {
$response = $row['0']->load();
}
echo $response;
Try this:
$response = [];
while ($row = oci_fetch_array($array)) {
$response[] = $row['0']->load();
}
var_dump($response);
I'm on PHP and I need to edit a JSON output to return only objects >=0 and divided by one hundred
Eg.
$json = {"data":[0,55,78,-32,-46,37]}
Needed
$json = {"data":[0,0.55,0.78,0.37]}
How this can be done?
Well, I know this is not the best practice, but if it's as simple as this, you can do the following.
$json = '{"data":[0,55,78,-32,-46,37]}';
// decoding the string to objects & arrays
$x = json_decode($json);
// applying a function on each value of the array
$x->data = array_map(
function($a)
{
if( $a >= 0 ) return $a/100;
else return null;
},
$x->data
);
// Removing empty values of the array
$x->data = array_filter($x->data);
// making a JSON array
$jsonData = json_encode(array_values($x->data));
// inserting a JSON array in a JSON Object
$json = '{"data":' . $jsonData . '}';
// here is your {"data":[0,0.55,0.78,0.37]}
echo $json;
Hope it helps !
Btw, I had to trick the json encode with array_values to prevent the creation of an object rather than an array for the data content. But I guess there is a better method that I just don't know ...
EDIT :
Find out the way :D
Once empty values removed from the array, just do :
$x->data = array_values($x->data);
$json = json_encode($x);
This will do the trick and it will not create issues with the rest of the object.
Alessandro:
Here's my approach, feel free to try. json_decode and a simple foreach can help you...
Code:
$json = array();
$result = array();
$json = '{"data":[0,55,78,-32,-46,37]}';
$decoded_json=json_decode($json, TRUE);
foreach ($decoded_json['data'] as &$value) {
if ($value >= 0){
$value = $value / 100;
$result[]=$value;
}
}
echo json_encode($result);
?>
Result:
[0,
0.55,
0.78,
0.37
]
How do I create an empty JSON array?
I tried $finalJSON["items"][0] = ''; but that gave me {"items":[""]}
I tried $finalJSON["items"][0] = null; but that gave me {"items":[null]}
What I actually want is {"items":[]}
How to achieve this?
Your code actually creates an array with already one element with key 0 and value '' (empty string) or null. Instead, use:
$finalJSON["items"] = array();
Try this:
$arr['items'] = array();
echo json_encode($arr);
You should set an empty array:
$finalJSON = [];
$finalJSON["items"] = [];
echo json_encode($finalJSON);
Output:
{"items":[]}
Example
Consider this example:
<?php
$items = [];
echo json_encode($items);
The output is: [].
That is the "most empty" array you can create and convert into a json encoding.
So if you want such an array as value inside an object as property item, then use an object:
<?php
class myObject {
public $items = [];
}
echo json_encode(new myObject);
The output is: {"items":[]}
$finalJSON["items"] = []; //short syntax
or
$finalJSON["items"] = array(); //old syntax
and to output:
echo json_encode($finalJSON);
This should work
<?php
$finalJSON["items"] = array();
echo json_encode($finalJSON);
?>