Php array of arrays to json in loop - php

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

Related

Need help to debug json response

I am trying to sent response in that form
{"files":[{"webViewLink":""},{"webViewLink":""}]}
But I'm getting response like that
{"files":[{"webViewLink":"""}]}{"files":[{"webViewLink":"""}]}
Here is my PHP code:
<?php
$idtemp = extractfiles($fol_id, $email);
foreach ($idtemp['items'] as $val) {
$id = $val['id'];
$val = array(
"webViewLink" => 'https://drive.google.com/file/d/'.$val['id'].'/view?usp=drivesdk"'
);
$enc = json_encode($val);
$val = '{"files":['.$enc.']}';
echo($val);
Please help me to fix code i need response in that way
{"files":[{"webViewLink":""},{"webViewLink":""}]}
You should no do $val = '{"files":['.$enc.']}';
Use json_encode to make json, don't do it manual
Create an object with desired keys outside the loop
Push anything to the desired array
Convert to json
<?php
$idtemp = extractfiles($fol_id, $email);
$json = (object) [
"files" => []
];
foreach ($idtemp['items'] as $val) {
$json->files[] = (object) [
"webViewLink" => 'https://drive.google.com/file/d/'.$val['id'].'/view?usp=drivesdk"'
];
}
$json = json_encode($json);
echo($json);
If I use some dummy values to create an example, the output is:
{
"files": [
{
"webViewLink": "https://drive.google.com/file/d/1/view?usp=drivesdk\""
},
{
"webViewLink": "https://drive.google.com/file/d/2/view?usp=drivesdk\""
},
{
"webViewLink": "https://drive.google.com/file/d/3/view?usp=drivesdk\""
}
]
}
As you can test in this online demo

How to properly format a JSON array | PHP

Essentially I have the following array with various values that are being passed through a function. The output of each needs to then be assembled into a JSON Array that looks like the following:
"response": {
"firstvalue": 4,
"secondvalue": 1,
"thirdvalue": "String Response 1",
"fourthvalue": "String Response 2"
}
Code So Far:
<?php
header('Content-Type: application/json');
$arrayvalues =
["34jkw9k2k9w",
"k4otk320el01oeoo20",
"30f0w2l020wk3pld==",
"3c2x3123m4k43=="];
foreach($arrayvalues as $item) {
$decrypted = myFunction($item, $action = 'decrypt');
$response["firstvalue"] = $decrypted;
$response["secondvalue"] = $decrypted;
$response["thirdvalue"] = $decrypted;
echo json_encode($response);
}
?>
How can this be done?
header('Content-Type: application/json');
$arrayvalues =
["34jkw9k2k9w",
"k4otk320el01oeoo20",
"30f0w2l020wk3pld==",
"3c2x3123m4k43=="];
// Is this necessary?
$keys = ['firstvalue', 'secondvalue', 'thirdvalue', 'fourthvalue'];
$result = [];
foreach($arrayvalues as $idx => $item) {
$result[$keys[$idx]] = myFunction($item, $action = 'decrypt');
}
echo json_encode(['response' => $result], JSON_PRETTY_PRINT);
UPD: Added response nesting.

PHP from loop to JSON formatting won't match

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

PHP how to make one sqaure bracket for all json object

The below is my php code.Many thanks
$data = array();
foreach ($row as $rowk) {
$data[] = array(
'message' => $row['traditionalmessage'],
'phone' => $row['telMobile']
);
break;
}
echo json_encode($data);
My current result
[{"message":"B\u578b\u809d\u708e\u75ab\u82d7\u4e0b\u4e00\u500b\u6ce8\u5c04\u671f\u4e3a2017-06-30\r\n","phone":"96709394"}][{"message":"\u75ab\u82d7\u540d\u7a314\u4e0b\u4e00\u500b\u6ce8\u5c04\u671f\u4e3a2017-06-30\r\n","phone":"96709394"}][{"message":"\u4fe1\u606f","phone":"55503234"}]
My desired result
[{"message":"B\u578b\u809d\u708e\u75ab\u82d7\u4e0b\u4e00\u500b\u6ce8\u5c04\u671f\u4e3a2017-06-30\r\n","phone":"96709394"},{"message":"\u75ab\u82d7\u540d\u7a314\u4e0b\u4e00\u500b\u6ce8\u5c04\u671f\u4e3a2017-06-30\r\n","phone":"96709394"},{"message":"\u4fe1\u606f","phone":"55503234"}]
In JSON arrays represented in [], and objects in {}, so in desired case you should have array of objects while you have array of arrays.
Try something like this:
$data = array();
foreach ($row as $rowk) {
$obj = new stdClass();
$obj->message = $row['traditionalmessage'];
$obj->phone = $row['telMobile'];
$data[] = $obj;
}
echo json_encode($data);

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