PHP from loop to JSON formatting won't match - php

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).

Related

how can produce json array with while in php

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;

Php array of arrays to json in loop

I am new in php, please help with my code.
I am trying to create PHP json for IOS app. Json should looks like this
{"items": [
{
"ID":12,
"name1":"some name",
"name2":"some name2"
},
{
"ID":13,
"name1":"another name",
"name2":"another name2"
},] }
Here is my PHP code part
$keys = array(ID, name1, name2);
while ($row = mysqli_fetch_array($result))
{
extract($row);
$values = array($row['ID'], $row['name1'], $row['name2']);
$response = array_combine($keys, $values);
header('Content-Type: application/json, charset=utf-8');
echo json_encode($response, JSON_UNESCAPED_UNICODE);
}
This gives me result like this
{
"ID":12,
"name1":"some name",
"name2":"some name2"
}
{
"ID":13,
"name1":"another name",
"name2":"another name2"
}
Can anybody help me with this?
Thanks in advance.
You need to build your array, and then encode the JSON outside of the loop for a start;
$keys = array(ID, name1, name2);
$items = array();
while ($row = mysqli_fetch_array($result))
{
extract($row);
$values = array($row['ID'], $row['name1'], $row['name2']);
$item = array_combine($keys, $values);
$items[] = $item;
}
header('Content-Type: application/json, charset=utf-8');
echo json_encode(array("items"=>$items), JSON_UNESCAPED_UNICODE);
Here we build up an array of your items into $items, and then encode them all outside of the loop.
Seems you are new or really don't know something about json yet
but i'll try to help you
just simply stored it in associative array an assign items as it's index
$response = array(
'items' => array_combine($keys, $values)
);
header('Content-Type: application/json, charset=utf-8');
echo json_encode($response, JSON_UNESCAPED_UNICODE);

how to add extra element to array with array_push in PHP?

I am developing in PHP/MS SQL for getting JSON Response.
Code which I wrote is:
while( $result = sqlsrv_fetch_object($sql_Gpo_Carr)) {
$array_res[] = $result; // add result to array
array_push($array_res, array('unidad' => $uni)); // add extra element
$jsonObj = json_encode($array_res); // encode JSON
}
echo $jsonObj;
exit();
This is what I want in result:
[{"idperiodo":"37","idgrupo":"1963","idhorario":"12832","unidades":null,"unidad":1}]
but the result shows me this:
[{"idperiodo":"37","idgrupo":"1963","idhorario":"12832","unidades":null},{"unidad":1}]
You're fetching an object. Add $uni to $result first and then add to $array_res:
while( $result = sqlsrv_fetch_object($sql_Gpo_Carr)) {
$result->unidad = $uni;
$array_res[] = $result;
}
Also, you probably want the json_encode() after the loop not in the loop:
echo json_encode($array_res);

Decoding json in array , editing array and encoding in json - PHP

I am newbee in php and trying to get json in array and wanna change key in that json below is my code :
$json = json_decode(file_get_contents('all_json_files/jobs.json'), true);
foreach ($json as $key=>$row){
foreach ( $row as $key=>$row){
foreach ( $row as $key=>$row){
foreach ($row as $key=>$row){
if(strcmp($key,"security_block")==0)
{
foreach ($row as $k=>$r){
if(strcmp($k,"job_payload_hash")==0)
{
$row[$k]['job_payload_hash']=$base64String;
print_r($row);
}
}
}
}
}
}
}
print_r($json);
Issue is print_r($row); is updating properly but print_r($json); does not print the updated string .
If the key could appear anywhere, the answer is pretty simple:
function update_hash(&$item, $key, $base64String)
{
if ($key == "job_payload_hash") {
$item = $base64String;
}
}
array_walk_recursive($json, 'update_hash', 'something');
Update
The structure is something different that previously assumed; while the above will work, probably the below is a more direct approach:
foreach (array_keys($json['jobs']) as $jobId) {
$json['jobs'][$jobId]['job']['security_block']['job_payload_hash'] = 'something';
}
You use $key & $row variable in multiple time. for this reason, value of $key is changed each time, so parent loop does not work..
You can use recursive function lik answer of #Ja͢ck .
this is because you have to save not in variables you defined after => in a foreach.
You have to store this in format:
$json[0][0] ... = $base64String;
OR
You have to add a new array like $result = array() before you write the foreach and then store it in $result.
Decode the JSON string using json_decode(), edit your resulting array, then use json_encode(); to return the array to a JSON encoded string.
Also, use array_key_exists() rather than comparing array key strings.
$array = json_decode($json);
if(array_key_exists("job_payload_hash", $array){
$array["job_payload_hash"] = base64encode($var);
}
$json = json_encode($array);

Json encode an entire mysql result set

I want to get json with php encode function like the following
<?php
require "../classes/database.php";
$database = new database();
header("content-type: application/json");
$result = $database->get_by_name($_POST['q']); //$_POST['searchValue']
echo '{"results":[';
if($result)
{
$i = 1;
while($row = mysql_fetch_array($result))
{
if(count($row) > 1)
{
echo json_encode(array('id'=>$i, 'name' => $row['name']));
echo ",";
}
else
{
echo json_encode(array('id'=>$i, 'name' => $row['name']));
}
$i++;
}
}
else
{
$value = "FALSE";
echo json_encode(array('id'=>1, 'name' => "")); // output the json code
}
echo "]}";
i want the output json to be something like that
{"results":[{"id":1,"name":"name1"},{"id":2,"name":"name2"}]}
but the output json is look like the following
{"results":[{"id":1,"name":"name1"},{"id":2,"name":"name2"},]}
As you realize that there is comma at the end, i want to remove it so it can be right json syntax, if i removed the echo ","; when there's more than one result the json will generate like this {"results":[{"id":1,"name":"name1"}{"id":2,"name":"name2"}]} and that syntax is wrong too
Hope that everybody got what i mean here, any ideas would be appreciated
If I were you, I would not json_encode each individual array, but merge the arrays together and then json_encode the merged array at the end. Below is an example using 5.4's short array syntax:
$out = [];
while(...) {
$out[] = [ 'id' => $i, 'name' => $row['name'] ];
}
echo json_encode($out);
Do the json_encoding as the LAST step. Build your data structure purely in PHP, then encode that structure at the end. Doing intermediate encodings means you're basically building your own json string, which is always going to be tricky and most likely "broken".
$data = array();
while ($row = mysql_fetch_array($result)) {
$data[] = array('id'=>$i, 'name' => $row['name']);
}
echo json_encode($data);
build it all into an array first, then encode the whole thing in one go:
$outputdata = array();
while($row = mysql_fetch_array($result)) {
$outputdata[] = $row;
}
echo json_encode($outputdata);

Categories