Return an Array instead of Object - php

I am fetching data from DB like this
$endResult = array();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
if (!isset($endResult[$row['car']])) {
$endResult[$row['car']]= (object) array(
'car' => $row['car'],
'carModel' => $row['carModel'],
'colors' => array()
);
}
$endResult[$row['car']] -> colors [] = (object) array(
'paintedOn' => $row['paintenOnDate'],
'paintedBy' => $row['paintedBy']
);
}
//return with slim.php
$response->body(json_encode($endResult));
and result I am getting
{"1":
{
"car": "1",
"carModel": "model-1",
"colors": [
{
"paintedOn": "2014-11-07",
"paintedBy": "5"
},{
"paintedOn": "2014-11-08",
"paintedBy": "6"
}]
},
"2":{
"car": "2",
"carModel": "model-2",
"colors": [
{
"paintedOn": "2014-11-09",
"paintedBy": "7"
},{
"paintedOn": "2014-11-10",
"paintedBy": "8"
}]
}
}//<--replace this with []
Even if $endResult is declared as Array I am getting {} brackets, how could I replace "Object" brackets with "Array" brackets?
UPDATE: I can't remove json_encode as the front-end (backbone) expecting collection
UPDATE 2: $endResult = array(); return [...]
but this $endResult[$row['car']]= (object) array(...) convert it to {...}

You can't achieve what you want because it would result in invalid JSON. According to json.org:
An array is an ordered collection of values. An array begins with [ (left bracket) and ends with ] (right bracket). Values are separated by , (comma).
So you can only have values in an array. Because you are adding a name to the value, it must become an object.
If you really want your JSON to be wrapped in an array you need to remove the first-level names, in your example "1" and "2":
[
{
"car": "1",
"carModel": "model-1",
"colors": [
{
"paintedOn": "2014-11-07",
"paintedBy": "5"
},
{
"paintedOn": "2014-11-08",
"paintedBy": "6"
}
]
},
{
"car": "2",
"carModel": "model-2",
"colors": [
{
"paintedOn": "2014-11-09",
"paintedBy": "7"
},
{
"paintedOn": "2014-11-10",
"paintedBy": "8"
}
]
}
]

Remove the conversion to JSON. Also "declaration" in PHP doesn't matter. You can still assign different types in the course of your program.

I think the PHP function json_decode Should help you here. This turns the JSON format into an array.

use json_decode($data,true) for convert returned data in to array.

simply use array_values function:
$array = array_values($response);

Related

Creating multi dimensional arrays, and handeling same key name issues for json_encode

I am trying to adhere to an integration requirement of having multiple items with the same key names, including its meta data into a main array to properly json_encode.
I have tried splitting out and joining arrays, array_push. The only workable solution I have is to manually build this part of the json package. Any help would be greatly appreciated.
Here is a sample of what I am struggling with:
$message_pack["Header"]["Sequence"] = 'TEST1';
$message_pack["Header"]["TC"] = "1";
$message_pack["ItemDetail"]["ItemName"] = "Item1";
$message_pack["ItemDetail"]["ItemCode"] = "123";
$message_pack["ItemDetail"]["Itemname"] = "Item2";
$message_pack["ItemDetail"]["ItemCode"] = "234";
$json_msg = json_encode($message_pack);
This will obviously only take the last value passed to the matching key name.
I need to adhere to this json format:
{
"Header": {
"Sequence": "TEST1",
"TC": "1",
},
"ItemDetail": [{
"ItemName": "Item1",
"ItemCode": "123" }
{ "ItemName": "Item2",
"ItemCode": "234" }]
}
You need to make "ItemDetail" an array, else you'll overwrite $message_pack["ItemDetail"]["Itemname"] and $message_pack["ItemDetail"]["ItemCode"]:
<?php
$message_pack["Header"]["Sequence"] = 'TEST1';
$message_pack["Header"]["TC"] = "1";
$message_pack["ItemDetail"][] = ["ItemName" => "Item1", 'ItemCode' => 123];
$message_pack["ItemDetail"][] = ["ItemName" => "Item2", 'ItemCode' => 234];
$json_msg = json_encode($message_pack, JSON_PRETTY_PRINT);
echo ($json_msg);
will output:
{
"Header": {
"Sequence": "TEST1",
"TC": "1"
},
"ItemDetail": [
{
"ItemName": "Item1",
"ItemCode": 123
},
{
"ItemName": "Item2",
"ItemCode": 234
}
]
}

Convert Single Object into an Array containing that Object

I have a number of JSON files and when there is a single object in them, their datatype is inconsistent. I am trying to alter the files that contain one item so that the element I am referencing is always an array.
Here's an example of a 'good' JSON file:
{
"apiv2": {
"items": [{
"id": "00001",
"name": "ITEM 1"
}, {
"id": "00002",
"name": "ITEM 2"
}]
}
}
In PHP terms, $json->apiv2->items is always an array I can apply the same functions to.
Every so often I have a JSON file that contains one item:
{
"apiv2": {
"items": {
"id": "00003",
"name": "ITEM 3"
}
}
}
When I attempt to iterate through 'items' with the same functions, they fail as it is now an object instead of an array.
My goal is to alter the JSON data and rewrite the file so the single item files are consistent with the multiple item files:
{
"apiv2": {
"items": [{
"id": "00003",
"name": "ITEM 3"
}]
}
}
Maybe it's because it's Friday afternoon, but I can't seem to wrap my head around this one. I thought it would be as simple as:
$json->apiv2->items = (array) $json->apiv2->items;
But that just turns it into an array with two elements, "id" and "name", not one element with the object.
As I said in the comments
When you do
$json->apiv2->items = (array) $json->apiv2->items;
PHP will convert $items to an actual array [ "id" => "00003", "name" => "ITEM 3"]
Which will give you the results ['items' => [ "id" => "00003", "name" => "ITEM 3"]]
Instead of converting your object, you need to wrap it
$json->apiv2->items = [$json->apiv2->items];
More advanced: since sometimes items can be an array and sometimes not, you can make a function [1] to wrap them
function wrap($value)
{
if (is_null($value)) {
return [];
}
return is_array($value) ? $value : [$value];
}
$json->apiv2->items = wrap($json->apiv2->items);
POC : https://3v4l.org/7p9b0
[1] Stolen from Laravel helpers
Use json_decode() and access it like this:
$json = '{"apiv2":{"items": [{"id": "00001", "name": "ITEM 1" }, {"id": "00002", "name": "ITEM 2" }]}}';
print_r(json_decode($json, true)['apiv2']['items']);

Laravel add seperate key-value pair to collection JSON

I have a Laravel controller that returns a collection of items (in this case Answers):
return AnswerResource::collection($correctAns);
This returns a JSON object as expected of course. How would I go about appending an item to that object so it's more like this?
{
"data": [
{
"id": "2",
"answer_text": "True"
},
{
"id": "3",
"answer_text": "False"
}
],
"testKey": "arsnteio12345"
}
(where the testKey thing is what's added)
Try something like this
return Response::json(['data '=> $correctAns, 'testKey' => 'arsnteio12345'],200);

print foreach loop with json_encode in php

I am new to php. so it may be very basic but I don't know it. So, I want to output like this in php using json_encode().
"option": [
{
"poOptionGroup": "11",
"optGrpID": "11",
"optGrpName": "Choose Backing Material"
},
{
"optID": "40",
"optName": "Black (Plexiglass)",
"optPriceDiff": "0"
},
{
"optID": "41",
"optName": "Clear (Plexiglass)",
"optPriceDiff": "18"
},
{
"optID": "218",
"optName": "Neon Stand Off",
"optPriceDiff": "18"
},
{
"optID": "219",
"optName": "White Plastic",
"optPriceDiff": "18"
}
],
"option": [
{
"poOptionGroup": "13",
"optGrpID": "13",
"optGrpName": "Any notes you want to include with your order"
},
{
"optID": "174",
"optName": "NO Thanks",
"optPriceDiff": "0"
},
{
"optID": "175",
"optName": "YES OUTDOOR",
"optPriceDiff": "170"
}
],
"SPIN3": [
{
"poOptionGroup": "56",
"optGrpID": "56",
"optGrpName": "Upgrade to OUTDOOR"
},
{
"optID": "44",
"optName": "",
"optPriceDiff": "20.02"
}
]
for this I have two nested foreach loop. which is as below:
$product=array();
foreach($query as $q){
$product['optGrpID']= $q['optGrpID'];
$product['optGrpName'] = $q['optGrpName'];
$product['poOptionGroup'] = $q['poOptionGroup'];
$opt_id=$product['optGrpID'];
$string= sql("select optID, optName, optPriceDiff from options where optGroup='$opt_id' ");
foreach ($string as $k=>$s){
$product['options']['optID']=$s['optID'];
$product['options']['optName']=$s['optName'];
$product['options']['optPriceDiff']=$s['optPriceDiff'];
}
}
so how can I achieve this desired output? please help. any help will be appreciate.
I am right in the proces of writing a PHP JSON API so I came across similar problems in the past few days. While I can't / don't want to solve your particular question about the PHP code, here is the most important thing I learned that I didn't find in many documentations or tutorials:
Giving json_encode() an associative array produces an JSON object with {key: value, key: value, ...}. Giving it a non-associative array produces a JSON list with [value, value, value, ...]. The values in the latter version can off course be objects them self ({...}). This means to get the structure you want, you have to pass the following array to json_encode:
array(
"option" => array(
array(
"optId" => "40",
"optName": "Black (Plexiglass)",
"optPriceDiff": "0"
),
array(
"optId" => "40",
"optName": "Black (Plexiglass)",
"optPriceDiff": "0"
),
.......
),
"SPIN3" => array(
array(
"poOptionGroup" => "56",
"optGrpID" => "56",
"optGrpName" => "Upgrade to OUTDOOR"
),
array(
"optID" => "44",
"optName" => "",
"optPriceDiff" => "20.0"
)
)
);
As you can see, some of those arrays are associative arrays, some of them are non-associative arrays acting as a "simple list". Knowing this, it should be easy to modify your PHP code to produce an array like the above and pass it to json_encode(). Unless you force json_encode() to allways produce JSON objects with a flag, PHP handles the conversion to JSON objects and JSON lists as seen above.
For correct terminology: "list" refers to JSON arrays, whereas associative arrays are converted to JSON objects with string-value-links. See the JSON website for details.

Accessing JSON encoded PHP Array in jQuery

I have an PHP Array which is formatted in the following format :
$jsonArray = array(
"facebook" => array("user" => "8", "user_id" => "10", "user_post" => "6"),
"twitter" => array("user" => "8", "user_id" => "10", "user_post" => "6")
);
I've then done the following so I can access the array
echo "<script type='text/javascript'>window.MyArray = ".json_encode($jsonArray).";</script>";
And to access the array I tried the following
alert(window.MyArray['facebook'][0]['user']);
yet that's seemed to fail, any directions?
window.MyArray['facebook'][0]['user']
--------------------------^^^
Why do you need [0] here?
Use this:
window.MyArray['facebook']['user']
MyArray gives this:
{
"facebook": {
"user": "8",
"user_id": "10",
"user_post": "6"
},
"twitter": {
...
}
}
MyArray['facebook'] results in the following array:
{
"user": "8",
"user_id": "10",
"user_post": "6"
}
Therefore, MyArray['facebook']['user'] results in 8.
try this way:
alert(window.MyArray.facebook.user);
it will work
You are passing the json as a string, you need to convert it to an object. To do that you can use http://www.json.org/js.html

Categories