JSON giving weird output in php - php

I'm learning php as well as JSON and can't figure out why I have following output:
JSON RESULT:
{
"Results": [
{
"user_id": "1"
},
{
"email": "user#example.com"
},
{
"first_name": "User"
},
{
"last_name": "One"
},
{
"password": "pass1"
},
{
"creation_date": null
},
{
"profile_type": "0"
},
{
"user_id": "2"
},
{
"email": "user2#example.com"
},
{
"first_name": "User"
},
{
"last_name": "Two"
},
{
"password": "pass2"
},
{
"creation_date": null
},
{
"profile_type": "0"
}
]
}
PHP:
<?php
require_once 'config/db.php';
$sql = new db();
$conn = $sql->connect();
$query = isset($_GET['query']) ? mysql_real_escape_string($_GET['query']) : "";
if(!empty($query))
{
$qur = mysql_query($query);
$result = array();
while($r = mysql_fetch_assoc($qur))
{
extract($r);
foreach($r as $key => $value)
{
$result[] = array($key => $value);
}
$json = array("Results" => $result);
}
}
#mysql_close($conn);
/* Output header */
header('Content-type: application/json');
echo json_encode($json, JSON_PRETTY_PRINT);
?>
My question is, why does it split each value into new record, I want each MySQL record to be one JSON record.

Just assign your row to $result:
while($r = mysql_fetch_assoc($qur))
{
$result[] = $r;
}
$json = array("Results" => $result);

It's doing this because of your for loop:
foreach($r as $key => $value)
{
$result[] = array($key => $value);
}
Maybe you should try something like json_encode on the data returned.
http://php.net/manual/en/function.json-encode.php
EDIT:
Try something like this:
$data = array();
while($row = mysqli_fetch_assoc($result))
{
$data[] = $row;
}
echo json_encode($data, JSON_PRETTY_PRINT);

I wouldn't use mysql to start with, use PDO. But if you must, you don't need foreach. Below will do.
while($r = mysqli_fetch_assoc($qur))
{
$result[] = $r;
$json = array("Results" => $result);
}

Related

Export database to json in a specific format

When Exporting database to json I get it in this form:
[
{
"id": "1",
"siteId": "1",
"siteUrl": "localhost",
"identity": "mobie",
"lastIp": "127.0.0.1",
"lastLogin": "2018-05-17",
"loginCountry": "GB",
}
]
Warning: Illegal string offset 'id' in C:\xamppp\htdocs\auth\mysql.php on line 81
To all of the $user variables.
My database structure is shown as above in the first json output.
Code
public function db2json($query){
$stmt = $this->db->prepare($query);
$stmt->execute();
$data=$stmt->fetch(PDO::FETCH_ASSOC);
$output = [];
foreach ( $data as $result ) { // Change this to loop over the data
$user = [];
$user["id"] = $result["id"];
$user["siteId"] = $result["siteId"];
$user["lastIp"] = $result["lastIp"];
$user["lastLogin"] = $result["lastLogin"];
$user["loginCountry"] = $result["loginCountry"];
$output[$result["siteUrl"]][$result["identity"]] = $user;
}
echo json_encode($output, JSON_PRETTY_PRINT);
}
I have had to build up some test data, but this will just mean that you change the foreach() to loop over your database result instead. Rather than just assigning the result straight to the output, this just creates the various arrays as you want them in the output...
$output = [];
foreach ( $data as $result ) { // Change this to loop over the data
$user = [];
$user["id"] = $result["id"];
$user["siteId"] = $result["siteId"];
$user["lastIp"] = $result["lastIp"];
$user["lastLogin"] = $result["lastLogin"];
$user["loginCountry"] = $result["loginCountry"];
$output[$result["siteUrl"]][$result["identity"]] = $user;
}
echo json_encode($output, JSON_PRETTY_PRINT);
With my test data, this outputs...
{
"localhost": {
"mobie": {
"id": "1",
"siteId": "1",
"lastIp": "127.0.0.1",
"lastLogin": "2018-05-17",
"loginCountry": "GB"
},
"user2": {
"id": "1",
"siteId": "1",
"lastIp": "127.0.0.1",
"lastLogin": "2018-05-17",
"loginCountry": "GB"
}
},
"othersite": {
"user1": {
"id": "1",
"siteId": "1",
"lastIp": "127.0.0.1",
"lastLogin": "2018-05-17",
"loginCountry": "GB"
}
}
}

Search in array in json file

I have an array which has a key with multiple content. I want to get that array which includes the key that I search .
$arr = json_decode('{"people":[
{
"id": "8080",
"content": "foo",
"member": [123, 456],
"interval": 7
},
{
"id": "8097",
"content": "bar",
"member": [1234, 4567],
"interval": 7
}
]}', true);
$results = array_filter($arr['people'], function($people) {
return $people['id'] == 8080;
});
echo json_encode($results);
This will return:
{"id":"8080","content":"foo","member":[123,456],"interval":7}
I want that:
$results = array_filter($arr['people'], function($people) {
return $people['member'] == 123;
});
And this does not work.
Have somebody an idea?
As #JonStirling said in comment. Use in_array() function.
$arr = json_decode('{"people":[
{
"id": "8080",
"content": "foo",
"member": [123, 456],
"interval": 7
},
{
"id": "8097",
"content": "bar",
"member": [1234, 4567],
"interval": 7
}
]}', true);
$searchId = 123;
$results = array_filter($arr['people'], function($people) use ($searchId) {
return in_array($searchId, $people['member']);
});
echo json_encode($results);
Result:
[{"id":"8080","content":"foo","member":[123,456],"interval":7}]
See if this helps:
$arr = json_decode('{"people":[
{
"id": "8080",
"content": "foo",
"member": [123, 456],
"interval": 7
},
{
"id": "8097",
"content": "bar",
"member": [1234, 4567],
"interval": 7
}
]}', true);
$results = array_filter($arr['people'], function($people) {
for($i=0; $i<count($people['member']); $i++){
return $people['member'][$i] == 123;
}
});
echo json_encode($results);
The out come will be:
[{"id":"8080","content":"foo","member":[123,456],"interval":7}]
If you want to do it withouth 'array_filter' you can try this:
function search($arr, $id, $arrayValue)
{
$people = null;
foreach ($arr['people'] as $a)
{
if ($a['id'] == $id)
{
$people = $a;
}
}
$arrayWeAreLookingFor = null;
foreach ($people as $property => $value)
{
if (is_array($value))
{
foreach ($value as $v)
{
if ($v == $arrayValue)
{
$arrayWeAreLookingFor = $people[$property];
}
}
}
}
return $arrayWeAreLookingFor;
}
var_dump(search($arr, 8080, 123));

Parsing array value with PHP in a foreach loop

I want to parse an array with PHP's foreach loop to get the object names and values inside the 'ques' array.I want
[
{
"ques": [
{
"name": "comment",
"value": "comment me for the reason",
"sur_id": "1",
"user_id": "admin#gmail.com",
"pagename": "question_response"
},
{
"name": "check-box[]",
"value": "1"
},
{
"name": "radio",
"value": "radio 2"
},
{
"name": "yes",
"value": "no"
}
]
"ques":[
{
"name": "date",
"value": "2015-10-23"
"user_id": "admin1#gmail.com",
},
{
"name": "select-deopdown",
"value": ""
},
{
"name": "true",
"value": "false"
},
{
"name": "number",
"value": "55"
}
]
}
]
I want to separate the name,value and user_id from the 'ques' array:
while ($fetch = mysql_fetch_array($query1)) {
$content = $fetch['CONTENT_VALUES'];
// print_r($content);
$content_value= mb_convert_encoding($content ,"UTF-8");
$datas = json_decode($content, true);
foreach($datas->ques as $values)
{
echo $values->value . "\n";
print_r($values);
}
$test[] = array('ques' => $datas ,'answer'=>$values);
}
If you want to make three different array for each value then create three blank array and then storing corresponding values into them in foreach . Am giving you a common example below
$name = array();
$values= array();
$users = array();
foreach($datas->ques as $values) {
$name[] = $values->name;
$values[] = $values->value;
$users[] = !empty($values->user_id) ? $values->user_id : '';
}
and further you can modify according your need.
Thank you.
This could help
$data = json_decode($json);
$result = [];
foreach($data as $row)
{
foreach($row as $k => $v)
{
$i = 0;
foreach($v as $key => $val)
{
foreach($val as $k1 => $v1)
{
$result[$i][$k1] = $v1;
}
$i++;
}
}
}
echo json_encode($result);
foreach($datas->ques as $values)
{
$name = $values['name'];
$value = $values['value'];
$user_id = $values['user_id'];
}
I solved this by following code.Thanks for 3 of them to guide by giving ideas.
$datas = json_decode($content, true);
foreach($datas as $values)
{
$name = $values['name'];
$value = $values['value'];
$user_id = $values['user_id'];
$test[]= array('user'=>$user,'name'=>$name,'value'=>$value);
}
}

JSON Output Array

I'm attempting to output my JSON in a format just like this: http://api.androidhive.info/json/movies.json and I am unsure of how to accomplish this through my PHP output code. Right now, It is displaying with "post" at the top and is a map, which I don't know how to successfully remove, seen here: http://shipstudent.com/complaint_desk/androidfriendsList.php?username=noah. Please let me know if you need more information.
PHP:
$rows = $stmt->fetchAll();
if ($rows) {
$response["posts"] = array();
foreach ($rows as $row)
{
$post = array();
$post["username"] = $row["username"];
$post["profile_picture"] = $row["profile_picture"];
array_push($response["posts"], $post);
}
// echoing JSON response
echo json_encode($response);
} else
{
die(json_encode($response));
}
JSON:
{
"posts": [
{
"username": "noah",
"profile_picture": "https://shipstudent.com/animal/appphotos/978321177.jpg"
},
{
"username": "e",
"profile_picture": "https://shipstudent.com/complaint_desk/appphotos/owl.jpeg"
},
]
}
Desired format:
[{
"title": "Dawn of the Planet of the Apes",
"image": "http://api.androidhive.info/json/movies/1.jpg",
"rating": 8.3,
"releaseYear": 2014,
"genre": ["Action", "Drama", "Sci-Fi"]
},
{
"title": "District 9",
"image": "http://api.androidhive.info/json/movies/2.jpg",
"rating": 8,
"releaseYear": 2009,
"genre": ["Action", "Sci-Fi", "Thriller"]
},
$rows = $stmt->fetchAll();
$response = [];
foreach ($rows as $row) {
$post = [
"username" => $row["username"],
"profile_picture" => $row["profile_picture"]
];
$response[] = $post;
}
echo json_encode($response);
$response = array();
foreach ($rows as $row)
{
$post = array();
$post["title"] => // define title;
$post["image"] => // define image;
$post["rating"] => // define rating;
$post["releaseYear"] => // define releaseYear;
$post["genre"] => // define genre, must be array();
array_push($response, $post);
}

Array inside a json object and object inside a json object using php

I am trying to produce the following JSON from MySQL database using PHP. How do I go about doing it in PHP lets say using the explode function for getting the array into the JSON object. I don't know about getting the JSON object inside an object. I just need to separate PHP files to achieve the following.
<?php
include 'database.php';
$pdo = Database::connect();
$sql = 'SELECT * FROM users';
$q = $pdo->prepare($sql);
$q->execute(array($sql));
$array = array();
while ($row = $q->fetch(PDO::FETCH_ASSOC)){
array_push($array, $row);
}
$json = json_encode($array);
echo $json;
Database::disconnect();?>
Array inside a JSON object:
[
{
"firstName":"John",
"lastName":"Doe",
"images": ['image1','image2','image3']
},
{
"firstName":"Anna",
"lastName":"Smith",
"images": ['image1','image2','image3']
},
{
"firstName":"Peter",
"lastName":"Jones",
"images": ['image1','image2','image3']
}
]
JSON object inside an object:
[
{
"firstName":"John",
"lastName":"Doe",
"cover": {
"cover_id": "0858699703",
"source": "www.myimages.co.zw/images/photo",
"offset_y": "0"
}
},
{
"firstName":"Anna",
"lastName":"Smith"
"cover": {
"cover_id": "0858699703",
"source": "www.myimages.co.zw/images/photo",
"offset_y": "0"
}
},
{
"firstName":"Peter",
"lastName":"Jones"
"cover": {
"cover_id": "0858699703",
"source": "www.myimages.co.zw/images/photo",
"offset_y": "0"
}
}
]
<?php
include 'database.php';
$pdo = Database::connect();
$sql = 'SELECT * FROM test';
$q = $pdo->prepare($sql);
$q->execute(array($sql));
$array = array();
while ($row = $q->fetch(PDO::FETCH_ASSOC)){
$row_array['name'] = $row['name'];
$row_array['surname'] = $row['surname'];
$row_array['images'] = explode(" ", $row['images']);
array_push($array, $row_array);
}
$json = json_encode($array);
echo $json;
Database::disconnect();
?>

Categories