php json_decode with data wrapped by [ ] - php

with true option, it works fine.
sorry and thanks guys.
=============================================
I encoded php array to json with this code
$rows = array();
if ($result = $mysqli->query($query)) {
while ($row = $result->fetch_assoc()) {
$rows[] = $row;
}
echo json_encode($rows);
/* free result set */
$result->free();
}
end decode with
$array = json_decode($server_output)
the $server_output is like this
[{"userid":"96679","userinfor":"xxxxxxxxx","userlocation":"CA"}]
[{"userid":"153795","userinfor":"xxxxxxxxx","userlocation":"CA"}]
[{"userid":"131878","userinfor":"xxxxxxxxx","userlocation":"CA"}]
but, $array is NULL :(
Thanks in advence,

This is not valid json together:
[{"userid":"96679","userinfor":"xxxxxxxxx","userlocation":"CA"}]
[{"userid":"153795","userinfor":"xxxxxxxxx","userlocation":"CA"}]
[{"userid":"131878","userinfor":"xxxxxxxxx","userlocation":"CA"}]
While, this part is valid:
[{"userid":"96679","userinfor":"xxxxxxxxx","userlocation":"CA"}]
or any one of them separately
$json = '[{"userid":"96679","userinfor":"xxxxxxxxx","userlocation":"CA"}]';
print_r(json_decode($json, true));
Output:
Array
(
[0] => Array
(
[userid] => 96679
[userinfor] => xxxxxxxxx
[userlocation] => CA
)
)
The valid format for all data is like this:
[
{
"userid": "96679",
"userinfor": "xxxxxxxxx",
"userlocation": "CA"
},
{
"userid": "153795",
"userinfor": "xxxxxxxxx",
"userlocation": "CA"
},
{
"userid": "131878",
"userinfor": "xxxxxxxxx",
"userlocation": "CA"
}
]

Related

create embedded json for autocomplete

I am using following code for making data coming from database as json format
public function employeeSearch()
{
$arrayOfEmployee = array();
$arrayToPush = array();
$arrayToJSON = array();
$new_item = $this->apicaller->sendRequest(array(
"controller" => "Employee",
"action" => "employeeSearch",
"searchCriteria" => "12345"
));
$arrayOfEmployee = json_decode($new_item,true);
foreach($arrayOfEmployee as $key => $employee)
{
$arrayToPush = array('data' => $employee['FullName'], 'value' => $employee['_id']['$oid']);
array_push($arrayToJSON, $arrayToPush);
}
echo json_encode($arrayToJSON);
}
The output is
[{"data":"Aasiya Rashid Khan","value":"5aa662b0d2ccda095400022f"},
{"data":"Sana Jeelani Khan","value":"5aa75d8fd2ccda0fa0006187"},
{"data":"Asad Hussain Khan","value":"5aaa51ead2ccda0860002692"},
{"data":"Ayesha Khan Khann","value":"5aab61b4d2ccda0bc400190f"},
{"data":"adhar card name","value":"5aaba0e1d2ccda0bc4001910"}
]
Now I want that json elements should look like
{
"suggestions": [
{
"value": "Guilherand-Granges",
"data": "750"
},
{
"value": "Paris 01",
"data": "750"
}
]
}
I have to implement this in jQuery autocomplete plugin...
Please help!!!
Replace the last line with
echo json_encode(["suggestions" => $arrayToJSON]);
This should result in the wanted result!
(This hold only true if you igonre the fact that the data in value and name is not the same/similar)

PHP ordering json array format

Im trying to get a json array, from a sql database which needs to be in the above format
{
"data":[
{
"name": "foo",
"age":"bar"
},
{
"name": "hello",
"age":"hi"
},
{
"name": "bar",
"age":"foo"
},
]
}
My code below return the data like,
{
"0": [
"name" : "blah",
"age" : "bleh"
],
"1": [
"name": "bleh",
"age" : "blah"
],
"data": []
}
CODE
$_SESSION['userID'] = $userID;
include('USERconfig.php');
$dataArray = array("data"=>array());
$sql = "SELECT name, age FROM dataQue";
$stmt = sqlsrv_query( $conn, $sql );
if( $stmt === false) {
die( print_r( sqlsrv_errors(), true) );
}
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
array_push($dataArray,
array("name"=>$row['name'],"age"=>$row['age']));
}
sqlsrv_free_stmt( $stmt);
header('Content-Type: application/json');
echo json_encode($dataArray);
exit();
How can i get all the data to be appended within the 'data' array?
And how can i get rid of the "0","1","2" ect.. ?
thanks in advance!
array_push() will insert data into the array after what you already have in it, I suggest you change the way you insert data in it by just calling back the array in the loop like this
$i = 0;
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
$dataArray['data'][$i]['name'] = $row['name'];
$dataArray['data'][$i]['age'] = $row['age'];
$i++;
}
this way all data retrieved from your query will be added to date index. By adding index ($i) will avoid replacing previous register.
You can use :
json_decode($dataArray);
add TRUE to json_decode like :
$dataArray = '{"data":[{"name": "foo","age":"bar"},
{"name": "hello","age":"hi"},
{"name": "bar","age":"foo"}]}';
print_r(json_decode($dataArray, true));
the result will be:
Array(
[data] => Array
(
[0] => Array
(
[name] => foo
[age] => bar
)
[1] => Array
(
[name] => hello
[age] => hi
)
[2] => Array
(
[name] => bar
[age] => foo
)
))

How to show JSON data with Associate Array Key?

in the below code, i used simple $key,$value but i want to use that code with associate array key. Then how can i do? Please help.
<?php
function custom_table_page_display() {
$jsonData = '{ "User":"John", "Age":22, "Country":"India" }';
$phpArray = json_decode($jsonData);
$rows = array();
foreach($phpArray as $key => $value)
{
$rows[] = $key;
$value1[]=$value;
}
$header=$rows;
$value11[]=$value1;
$output = theme('table',array('header'=>$header,'rows' => $value11));
return $output;
}
?>
You need to use
$phpArray = json_decode($jsonData, true);
The second argument says whether to return an associative array or object for a JSON object. By default it returns an object.
You can replace your foreach loop with:
$rows = array_keys($phpArray);
$value1 = array_values($phpArray);
For the data you gave in the comment below, you would do:
$rows = array_keys($phpArray['Class'][0]);
$values = array_map('array_values', $phpArray['Class']);
$values will then be a 2-dimensional array of values:
[ [ "John", 22, "India" ],
[ "Sam", 23, "Argentina" ],
[ "John", 22, "Algeria" ]
]
DEMO

Two queries mysql in one object json

I have two tables that I want to convert them to json like this:
[
{
"date":"2013-07-20",
"id":"123456",
"year":"2013",
"people":[
{
"name":"First",
"age":"60",
"city":"1"
},
{
"name":"second",
"age":"40",
"city":"2"
},
{
"name":"third",
"age":"36",
"city":"1"
}
]
}
]
but the result of my code is this:
[
{
"date":"2013-07-20",
"id":"123456",
"year":"2013",}
,{
"people":[
{
"name":"First",
"age":"60",
"city":"1"
},
{
"name":"second",
"age":"40",
"city":"2"
},
{
"name":"third",
"age":"36",
"city":"1"
}
]
}
]
the code creates a new object to the array "people" and I want that are in the same object
$result = mysql_query("SELECT * FROM data where id='123456'");
$fetch = mysql_query("SELECT name,age,city FROM people where id='123456'");
$json = array();
$json2['people'] = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)){
$json[] = $row;
}
while ($row = mysql_fetch_assoc($fetch)){
$row_temp["name"]=$row["name"];
$row_temp["age"] = $row["age"];
$row_temp["city"] = $row["city"];
array_push($json2['people'],$row_temp);
}
array_push($json, $json2);
echo Json_encode($json);
How I can make the array is in the same object as the table "data"?
Many thanks
I think you may try this
$result = mysql_query("SELECT * FROM data where id='123456'");
$fetch = mysql_query("SELECT name,age,city FROM people where id='123456'");
// I think, you'll get a single row, so no need to loop
$json = mysql_fetch_array($result, MYSQL_ASSOC);
$json2 = array();
while ($row = mysql_fetch_assoc($fetch)){
$json2[] = array(
'name' => $row["name"],
'age' => $row["age"],
'city' => $row["city"]
);
}
$json['people'] = $json2;
echo json_encode($json);
Result of print_r($json) should be something like this
Array
(
[date] => 2013-07-20
[year] => 2013
[id] => 123456
[people] => Array
(
[0] => Array
(
[name] => First
[age] => 60
[city] => 1
)
[1] => Array
(
[name] => second
[age] => 40
[city] => 2
)
)
)
Result of echo json_encode($json) should be
{
"date" : "2013-07-20",
"year":"2013",
"id":"123456",
"people":
[
{
"name" : "First",
"age" : "60",
"city" : "1"
},
{
"name" : "second",
"age" : "40",
"city" : "2"
}
]
}
If you do echo json_encode(array($json)) then you will get your whole json wrapped in an array, something like this
[
{
"date" : "2013-07-20",
"year":"2013",
"id":"123456",
"people":
[
{
"name" : "First",
"age" : "60",
"city" : "1"
},
{
"name" : "second",
"age" : "40",
"city" : "2"
}
]
}
]
You were very close, but you want the People array to be a direct value of the outer array and you've wrapped it in an extra array.
Also, please note that the MySQL library you are using is deprecated. That means it will be removed from PHP in a future release. You should replace calls from the MySQL_* family of functions with either mysqli or pdo
$result = mysql_query("SELECT * FROM data where id='123456'");
$fetch = mysql_query("SELECT name,age,city FROM people where id='123456'");
$json = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)){
$json[] = $row;
}
$json['people'] = array();
while ($row = mysql_fetch_assoc($fetch)){
$row_temp["name"]=$row["name"];
$row_temp["age"] = $row["age"];
$row_temp["city"] = $row["city"];
array_push($json['people'],$row_temp);
}
echo Json_encode($json);
You can make it work by waiting to use the key people until the very end when you join the two arrays. Up until then, just load the data into $json and $json2.
$json = array('date' => '2013', 'id' => '123456', 'year' => '2013');
$result = mysql_query("SELECT * FROM data where id='123456'");
$fetch = mysql_query("SELECT name,age,city FROM people where id='123456'");
$json = array();
$json2 = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)){
$json[] = $row;
}
while ($row = mysql_fetch_assoc($fetch)){
$row_temp["name"]=$row["name"];
$row_temp["age"] = $row["age"];
$row_temp["city"] = $row["city"];
array_push($json2, $row_temp);
}
$json['people'] = $json2;
echo Json_encode($json);

How to get values from nested JSON data?

Here's my JSON code:
{
"query": {
"count": 2,
"created": "2013-04-03T09:47:03Z",
"lang": "en-US",
"results": {
"yctCategories": {
"yctCategory": {
"score": "0.504762",
"content": "Computing"
}
},
"entities": {
"entity": [
{
"score": "0.902",
"text": {
"end": "19",
"endchar": "19",
"start": "0",
"startchar": "0",
"content": "Computer programming"
},
"wiki_url": "http://en.wikipedia.com/wiki/Computer_programming"
},
{
"score": "0.575",
"text": {
"end": "51",
"endchar": "51",
"start": "41",
"startchar": "41",
"content": "programming"
}
}
]
}
}
}
}
and below is my PHP code
$json_o = json_decode($json,true);
echo "Json result:</br>";
echo $json; // json
echo "</br></br>";
echo "Value result:</br>";
$result = array();
//$entity = $json_o['query']['results']['entities']['entity'];
foreach ($json_o['query']['results']['entities']['entity'] as $theentity)
foreach ($theentity['text'] as $thetext){
$result[] = $thetext['content'];
}
print_r($result);
My expectation is to get the value of content in entity, which is "Computer programming" and "programming".
I already searching around, but still have found the solution yet.
The result of my PHP code is:
Array ( [0] => 1 [1] => 1 [2] => 0 [3] => 0 [4] => C [5] => 5 [6] => 5 [7] => 4 [8] => 4 [9] => p )
Use this loop
foreach ($json_o['query']['results']['entities']['entity'] as $theentity)
{
$result[] = $theentity['text']['content'];
}
http://codepad.viper-7.com/tFxh1w
Output Array ( [0] => Computer programming [1] => programming )
Change your foreach to:
$result = array();
foreach ($json_o['query']['results']['entities']['entity'] as $theentity) {
$result[] = $theentity['text']['content'];
}
print_r($result);
$theentity['text'] is an array of keys => value. You can just access key content instead of looping through all of the entries.
Another way you could do it (though it is a poor choice) is:
foreach($theentity['text'] as $key => $value) {
if( 'content' === $key ) {
$result[] = $value;
}
}
I provide this second example to demonstrate why the original code did not work.
Update
To access other properties like the yctCategories just do something similar
$categories = array();
foreach ($json_o['query']['results']['yctCategories'] as $yctCategory) {
$categories[] = $yctCategory['content'];
}
print_r($categories);
remove the second foreach and replace it with $result[] = $theentity['text']['content'];
using something like http://jsonlint.com/ might make it easier for you to see how the json is structured. alternatively just var_dump (or print_r) the output of your json_decode.
Use simple code:
$array = $json_o['query']['results']['entities']['entity'];
foreach($array as $v){
echo $v['text']['content'];
}

Categories