How to echo JSON doubly nested object literal w/ proper "headers" - php

I'm trying to simply echo a JSON object literal which includes every row in my database table.
As standard with the methods found in many other similar questions I looked at, I'm fetching every row and encoding it like so:
$con=mysqli_connect("localhost","username","pass","markers");//markers is db table name
$result = mysqli_query($con,"SELECT * FROM markers");
$rows = array();
while($r = mysqli_fetch_array($result))
{
$rows[] = $r
//or: $rows[] = array('data' => $r);
}
echo json_encode($rows);
Similarly to the question PHP: can't encode json with multiple rows or mysql table to json ,
I want to echo a JSON Object which looks like this:
{
"data1": // how do I get "data1"?
{
name: John Smith,
title: Mr,
description: a man
}
}
{
"data2":{ // how do I get "data2"?
name:Bob Smith,
title: Mr,
description: another guy
}
}
Except I do not get how to achieve the "headers", the titles of the first level string of objects, such as "data1" or data2". In fact, my database table doesn't necessarily even have those values/that column.
This is what it looks like right now:
How can I get simply numerical "headers" like "1", "2" or "data1", "data2" without having to designate the "name" column as the "headers"? (Or do I have to have a column for that?)
My goal is to process the values in every "row" in the returned JSON.
I plan to use the jQ $.each function $.each(data, function(dataNum, dataInfo) -- e.g. data1 would be passed to dataNum and the values would be passed to dataInfo -- and be able to access specific table values by dataInfo.name, which right now is not working.
Thanks to any help in advance!

I would think you are way better off using mysqli_fetch_object() to get each row as it own object. When you then json_encode $rows you would have an array of objects.
Here is the code:
$con=mysqli_connect("localhost","username","pass","markers");//markers is db table name
$result = mysqli_query($con,"SELECT * FROM markers");
$rows = array();
while($r = mysqli_fetch_object($result))
{
$rows[] = $r;
}
echo json_encode($rows);
Your JSON would look like this:
[
{
"name":"Some Name",
"title":"Some Title",
"description":"Some description"
},
{
"name":"Some Other Name",
"title":"Some Other Title",
"description":"Some other description"
},
...
]
In javascript, that gives you an integer-indexed array of objects. So your javascript might look like this:
var array = JSON.parse(jsonString);
$.each(array, function(key, value) {
alert(key); // numerical index
alert(value.name); // name
alert(value.title); // title
alert(value.description); // description
});

Create indexes in your $rows variable:
<?php
$t['a'] = array ('name' => 'foo');
$t['b'] = array ('name' => 'bar');
echo json_encode ($t);
?>
In your case, a simple integer should do the trick, or something like $rows['data' . $i] followed by a $i++.

Related

JSON object with array header

this question comes from the posting I found here:
DataTables Multiple Tables from Multiple JSON Arrays
I'd like to know the simplest and best way to generate the JSON below. I can see the pattern is 'JSON object -> Array Header -> Array -> JSON object' but I do not know how to do this in PHP, from a mySQLi query result. I imagine having a mySQL table with a 'policies' and 'services' column so the query might look something like:
Select name, id, score, type from myTable where type = 'policies' and
type = 'services'
And the result would come back something like:
name id score type
A 1 0 policies
B 2 0 services
But then how would I take that query and generate this JSON in php?
{
"Policies": [
{
"name": "A",
"id": "1",
"score": "0"
}
],
"Services": [
{
"name": "B",
"id": "2",
"score": "0"
}
]
}
Thanks for your help!
Start by creating the new empty array.
Then, iterate through the result and add it in the correct sub-array:
$new = [];
foreach ($result as $item) {
// Uppercase the first character
$type = ucfirst($item['type']);
if (!isset($new[$type])) {
// This type doesn't exist in the new array yet, let's create it.
$new[$type] = [];
}
// Add the item
$new[$type][] = $item;
}
// Output it as json
echo json_encode($new, JSON_PRETTY_PRINT);
The above code will also work if new types are added to the database.
PS. The JSON_PRETTY_PRINT argument is just to make the json string a bit more readable while developing. When everything looks good, you can remove it.

How do I prepare multidimensional array from php mysql query for jQuery autocomplete?

I am trying to set up a jQuery autocomplete that uses results from a PHP MySql query.
I have the basic autocomplete working for a 1-d array of values, but can't get it to work with a 2-d array. I want to use a 2-d array so that one column populates the auto-complete and one column populates the value submitted in the form (either through the value of the input or another hidden value).
I know the format needs to look like this after using json_encode(): [ { label: "Choice1", value: "value1" }, ... ] but can't quite get it to look like that...
The code below is not my working code but it represents what I would like to do: display the names in the autocomplete field, but submit the page_id.
Here is my code:
$query = "SELECT name, page_id FROM table WHERE city = '{$location}' ORDER BY name";
$result = $mysqli->query($query);
while($row = mysqli_fetch_assoc($result)){
$array[] = $row;
}
<script>
$( function() {
var array = <?php echo json_encode($array); ?>;
$( "#input" ).autocomplete({
source: array
});
} );
</script>
When you want to distinguish value and label, you must provide an array of objects, as described in the jQuery autocomplete documentation:
source
Array: An array can be used for local data. There are two supported formats:
An array of strings: [ "Choice1", "Choice2" ]
An array of objects with label and value properties: [ { label: "Choice1", value: "value1" }, ... ]
As you are looking for that second option you should in PHP prepare that exact structure. This you can do as follows:
while($row = mysqli_fetch_assoc($result)){
$array[] = array(
"label" => $row['name'],
"value" => $row['page_id']
);
}
This adds so-called associative arrays into the normal (indexed) array. json_encode translates associative arrays into object notation.

Count number of elements in an array in javascript (not length)

I've got an array with different "columns", for example: id, title, date, data etc.
It is a JSON array.
The data element has multiple entries:
"data":["test = test", "2nd test", "3rd test"]
How can I find how many entries there are in the "data" element of the "result" array?
When I try result.data.length, it gives me the whole length, so all the characters.
Here, it would say something like 27, while I want 3 as an answer.
EDIT: this is how I get the elements and push them (I get a JSON array):
$.getJSON("test.php?id=" + id, function(data) {
$.each(data, function(index, data1) {
window.result.push(data1);
});
And this is the test.php code:
if(isset($_GET['id'])){
$id = $_GET['id'];
$liste = getData($id);
$arr = array();
$i = 0;
foreach($liste as $result){
$arr[$i]['id'] = $result->id();
$arr[$i]['titre'] = $result->titre();
$arr[$i]['data'] = $result->listeMot();
$i++;
}
echo json_encode($arr);
Thanks for the help.
The answer was finally found (thanks a lot to #RocketHamzat).
It was indeed a string, and not an array. In that case, I had returns after each pair of words (I thought they were separated by commas, but they weren't).
So, to count, this is what I did:
result.data.split('\r\n').length;
This worked like a charm. Thanks for your help!
I agree with the comments posted - your return object does not look as if it is formatted properly. data should be an object with a key value of the array. Your return should look like the following:
var d = '{"data":["test = test", "2nd test", "3rd test"]}';
console.dir(JSON.parse(d));
var arr = JSON.parse(d);
console.log(arr.data.length);
The console.dir will display the object, and the console.log displays a length of 3.
Are you formatting the response as a JSON string manually? If so wrap with {}
Hope that helps.

how to use json_encode

I'm dealing with highcharts with dynamic data (values retrieved from database).
By writing a query i was able to retrieve the following data from the table
Item 2011 2012
pen 5 7
pencil 4 20
eraser 6 43
I want to store the above info in the following structure and pass it to another page
[{ name:'pen', data: [5,7]},{ name:'pencil', data: [4,20]},{ name:'eraser', data: [6,43]}]";
I want to push the above data to the drilldown highchart.
Is there a way i can generate in this format? I've tried using json_encode but unable to succeed.
Can i achieve this using json_encode?
Updated
I've tried in this way
while($row = mysql_fetch_assoc($result))
{
$rows[]= $row;
}
echo json_encode($rows);
and got
[{"Item":"pen","2011":"5","2012":"7"},{"Item":"pencil","2011":"4","2012":"20"},{"Item":"eraser","2011":"6","2012":"43"}]
json_encode is a convenience method to convert an array into JSON format. To have the output you provided, you will need an array of arrays. Each sub-array has keys "name" and "data", where "name" is the Item column, and "data" is another array containing values from 2011 and 2012.
$results = mysql_query("...");
$arr = array();
while ($row = mysql_fetch_assoc($results))
{
$name = $row['Item'];
$data = array($row['2011'], $row['2012']);
$arr[] = array('name' => $name, 'data' => $data);
}
echo json_encode($arr);
Loop through the database results and put the results in an array
JSON encode the array

PHP json_encode return rows as arrays instead of objects

From my experience, when I json_encode data from a mysql table, the output is an object containing each row as an object within. What I want to do is to get each row as an array, like the example below (don't need the column names in there). How can I do that?
{ "Data": [
["1","Internet Explorer 4.0","Win 95+","4","X","1"],
["2","Internet Explorer 5.0","Win 95+","5","C","2"],
["3","Internet Explorer 5.5","Win 95+","5.5","A","3"],
["4","Internet Explorer 6","Win 98+","6","A","4"],
] }
Use mysql_fetch_row [docs] to get each row. This will get a row as a numerical array and those are also encoded as JSON arrays:
$data = array();
while(($row = mysql_fetch_row($result))) {
$data[] = $row;
}
echo json_encode(array('Data' => $data));
NOT CHECKED in interpreter:
You can change the type of variable by simple types convertion:
$data = DB::get('SELECT * FROM `table` WHERE 1');
echo json_encode(array('Data' => (array)$data));
Also you can use next function: array mysql_fetch_array ( resource $result [, int $result_type ] )

Categories