PHP ordering json array format - php

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

Related

How to create nested tag in JSON

I have been fiddling with JSON nested tag, tried the basics now I want to go a little further, but it has been giving a little head ache to me. I have this public function below
public function returnResponse($code, $data){
header("content-type: application/json");
$result = json_encode(['response' => ['status' => $code, "message" => $data]]);
echo $result ; exit;
}
$order= $cust->getDeliveryDetail();
USING print_r($order);
Array
(
[0] => Array
(
[0] => Array
(
[order_id] => 4444
[menu] => two
[order_uniq] => 999oeo4
)
)
[1] => Array
(
[0] => Array
(
[pro_name] => Beans
[pro_sub] => Goods
[pro_type] => Open CA
)
[1] => Array
(
[pro_name] => Rice
[pro_sub] => Fiber
[pro_type] => Diverca
)
)
)
then attaching object with elements and value which references
$result ['order_id'] = $order[0][0]['order_id'];
$result ['menu'] = $order[0][0]['menu'];
$result ['order_uniq'] = $order[0][0]['order_uniq'];
$result ['pro_name'] = $order[0][0]['pro_name'];
$result ['pro_sub'] = $order[0][0]['pro_sub'];
$result ['pro_type'] = $order[0][0]['pro_type'];
$this->returnResponse(SUCCESS_RESPONSE, $result); //THIS IS THE ORIGINAL BEGINNING PUBLIC FUNCTION WE CREATED
to create this JSON nested tag below
{
"response": {
"status": 200,
"message": {
"order_id": "4444",
"menu": "two",
"order_uniq": "999oeo4",
"pro_name": "Beans",
"pro_sub": "Goods",
"pro_type": "Openca",
}
}
}
but I want to create a JSON nested tag like this below
{
"response": {
"status": 200,
"message": {
"order_id": "4444",
"menu": "two",
"order_uniq": "999oeo4",
"items": [
{
"pro_name": "Beans",
"pro_sub": "Goods",
"pro_type": "Openca",
}
{
"pro_name": "Rice",
"pro_sub": "Fiber",
"pro_type": "Diverca",
}
]
},
}
}
If it helps -- maybe not, the right way to do this in the beginning would be to create an OrderItems table/dictionary. Then store items in that table referrencing your Order table with "order_id". That way you could pull order_items as one array object, and convert that to json really simply.
Here since, you are getting "pro_name", "pro_sub" & "pro_type" as items, you would programmatically pull those out and create your own order_items array.
$order= $cust->getDeliveryDetail();
$order_id = $order[0][0]['order_id'];
$order_menu = $order[0][0]['menu'];
$order_uniq = $order[0][0]['order_uniq'];
$items = [];
foreach($order[1] as $order_item) {
$items[] = $order_item;
}
$result = [];
$result["order_id"] = $order_id;
$result["menu"] = $order_menu;
$result["order_uniq"] = $order_uniq;
$result["order_items"] = $items;
$this->returnResponse(SUCCESS_RESPONSE, $result);
Like this?
$result = array(
'order_id' = > $order[0][0]['order_id'],
'menu' => $order[0][0]['menu'],
'order_uniq' => $order[0][0]['order_uniq'],
'pro_name' => $order[0][0]['pro_name'],
'pro_sub' => $order[0][0]['pro_sub'],
'pro_type' => $order[0][0]['pro_type'],
'items' => array()
);
foreach($order[1] as $item) {
array_push(
$result['items'],
array(
'pro_name' => $item['pro_name'],
'pro_sub' => $item['pro_sub'],
'pro_type' => $item['pro_type'],
)
);
}

Mapping SQL query results to JSON in PHP

I'm running into some issues getting the correct JSON output from my SQL query. Essentially what I'm struggling with is getting an array of options objects as opposed to singular option objects.
$query = 'SELECT matchup.matchupID, matchup_option.player_name, matchup_option.player_id FROM matchup
INNER JOIN matchup_option
ON matchup_option.matchupID= matchup.matchupID;';
$attachments = $db->query($query);
$data = array();
while ($attachment = $db->fetch_array($attachments)){
$data[] = array (
'id' => $attachment['matchupID'],
'options' => array(
array (
"name" => $attachment['player_name'],
"playerid" => $attachment['player_id']
)
)
);
//VAR_DUMP($attachment);
}
$data = array("matchup"=>$data);
print json_encode($data);
Gives me this output:
{
"matchup":[
{
"id":"111222",
"options":[
{
"name":"111",
"playerid":"111"
}
]
},
{
"id":"111222",
"options":[
{
"name":"222",
"playerid":"222"
}
]
}
]
}
And here's what I'm trying to get to:
{
"matchup":[
{
"id":"111222",
"options":[
{
"name":"111",
"playerid":"111"
},
{
"name":"222",
"playerid":"222"
}
]
}
]
}
I'd like to follow best practices as well as structure this appropriately, if there's a better way to go about this, please let me know!
You need to store $attachment['matchupID'] as an array key of $data:
$data = array();
while ($attachment = $db->fetch_array($attachments)){
if (!isset($data[$attachment['matchupID']])) {
$data[$attachment['matchupID']] = array (
'id' => $attachment['matchupID'],
'options' => array()
);
}
$data[$attachment['matchupID']]['options'][] = array (
"name" => $attachment['player_name'],
"playerid" => $attachment['player_id']
);
}
// use `array_values` to reindex `$data`
$data = array("matchup" => array_values($data));
print json_encode($data);

Prepend key value to array - PHP

I have the below code in a for..loop is there a way I can add values to the beginning of the array?
$data = array();
$initial = strtotime('11:00:00');
for (; $initial < strtotime("23:00:59"); $initial = strtotime("+15 minutes", $initial)) {
if ($initial > strtotime("+45 minutes", time())) {
$row['value'] = date('Hi', $initial);
$row['label'] = date('H:i', $initial);
$data['data'][] = $row;
}
}
I want to add the below values to the top of the array. I have tried using array_unshift but I don't think it supports key-value pairs.
if(!isBetween('22:00', '09:59', date('H:i'))) {
$row['value'] = "asap";
$row['label'] = "ASAP";
}
My array output
{
"data": [
{
"value": "1145",
"label": "11:45"
}
]
}
I want to get this
{
"data": [
{
"value": "asap",
"label": "ASAP"
},{
"value": "1145",
"label": "11:45"
},
]
}
Un-shift should work if you pass the arguments correctly:
array_unshift($data["data"], $prepend);
Alternatively, you could use array_merge, like this:
$data["data"] = array_merge(array($prepend), $data["data"]);
With the following example data:
$data = [
"data" => [
[
"value" => "1145",
"label" => "11:45"
]
]
];
$prepend = [
"value" => "asap",
"label" => "ASAP"
];
$data["data"] = array_merge(array($prepend), $data["data"]);
print_r($data);
You would get this output (with both solutions):
Array (
[data] => Array (
[0] => Array (
[value] => asap
[label] => ASAP
)
[1] => Array (
[value] => 1145
[label] => 11:45
)
)
)
If you need to prepend something to the array without the keys being reindexed and/or need to prepend a key value pair, you can use this short function:
function array_unshift_assoc(&$arr, $key, $val) {
$arr = array_reverse($arr, true);
$arr[$key] = $val;
return array_reverse($arr, true);
}
Source: http://php.net/manual/en/function.array-unshift.php

php json_decode with data wrapped by [ ]

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"
}
]

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

Categories