How to format JSON output in Symfony - php

I have a script that expects the following output:
[{
"id": "288",
"title": "Titanic",
"year": "1997",
"rating": "7.7",
"genre": "drama, romance",
"od": "0"
}, {
"id": "131",
"title": "The Bourne Identity",
"year": "2002",
"rating": "7.9",
"genre": "action, mystery, thriller",
"od": "1"
}]
That does not look like well formatted json, as when I do this:
return new JsonResponse(array(
"id" => 288,
"title" => "Titanic",
"year" => "1997",
....
));
I am getting this:
{
"id": ​288,
"title": "Titanic",
"year": "1997"
....
}
The plugin I am using is this, and it even has a $.getJson Function?!?
How would I change the output format?

its just missing its outer container.
try this:
return new JsonResponse( array( array(
"id" => 288,
"title" => "Titanic",
"year" => "1997"
)) );
this should output as:
[{"id":288,"title":"Titanic","year":"1997"}]

You have to include the items array into a parent one:
return new JsonResponse(array(
array(
"id" => 288,
"title" => "Titanic",
"year" => "1997",
....
),
array(
"id" => 288,
"title" => "Titanic",
"year" => "1997",
....
)
));

You have to put your data in another array to create an array of items. Just wrap the existing array in another array:
return new JsonResponse(array(
array(
"id" => 288,
"title" => "Titanic",
"year" => "1997",
....
)
));

Related

Laravel api foreach argument must be of type array|object, null given in

i am getting product data from API end.
there are two nested "data" in the incoming array.
i can list the products with foreach, but I can't reach a single element.
when I try a few methods, it returns errors like "array,object int". Where am I going wrong and how can I access its elements?
the method i'm trying now is this and i'm applying this process on the Laravel side.
{
"data": {
"data": [
{
"id": 101553,
"company_id": 730,
"category_id": 132288,
"brand_id": 39549,
"name": "Hh PRODUCT TEST",
"remote_category_id": "scarf",
"remote_brand_id": "bershka123",
"spu": "zb3940823904"
},
{
"id": 101554,
"company_id": 730,
"category_id": 132289,
"brand_id": 39549,
"name": "Hs PRODUCT TEST",
"remote_category_id": "scarf",
"remote_brand_id": "bershka123",
"spu": "zb3940823905"
}
],
"count": 175,
"search": {
"category_id": null,
"brand_id": null,
"company_id": null
},
"start": 0,
"length": 10
},
"error_code": 0,
"message": ""
}
Model:
public function getProducts($start =0, $length =10, $category_id =null, $brand_id=null, $spu=null, $name=null, $is_active=null, $id=null, $remote_brand_id = null, $remote_category_id=null)
{
$request = Http::withHeaders([
'Authorization' => 'Bearer '.$this->jwttoken,
'Content-Type' => 'application/json'
])->post($this->sandbox . 'products/search',[
"start" => $start,
"length" => $length,
"search" => [
"category_id" => $category_id,
"brand_id" => $brand_id,
"spu" => $spu,
"name" => $name,
"is_active" => $is_active,
"id" => $id,
"remote_brand_id" => $remote_brand_id,
"remote_category_id" => $remote_category_id
]
])->json();
return $request;
}
controller
$company_id = 100;
$products = (new Client($company_id))->getProducts();
foreach($products as $product){
foreach($product as $prd){
dump($prd);
}
}
Result:
0 => array:27 [
"id" => 101530
"company_id" => 730
"category_id" => 132047
"brand_id" => 39316
"name" => "Hs Test Shoe"
"remote_category_id" => "5a39b114f1ff6e42639e9e041cd002d6"
"remote_brand_id" => "617392d2b51dbba1a2e5561a3e4eefe7"
"spu" => "845504"
],
1 => array:36 [
"id" => 231303
"company_id" => 730
"product_id" => 101530
"supplier_id" => null
"remote_supplier_id" => null
"name" => "Hd Test Shoe"
"description" => "This is a test product."
"sku" => "2K4F9966WHITE42"
]
ErrorException :
foreach() argument must be of type array|object, int given
How do i get the correct loop format and elements?
You have to loop like this way
foreach($products["data"]["data"] as $product)
{
dump($product);
}

Need a help to assign array to array element of php

I have created an array to convert into json file in php. But as per the requirement I need to assign an array to this array element. it's an array inside an array.
"data" => array( // data array
array(
"event_name" => "Purchase",
"event_time" => time(),
"event_id" => $order_id,
"user_data" => array(
"client_ip_address" => $ip,
"client_user_agent" => $browser,
"em" => $email,
"ph" => $phone,
"fbc" =>$fbp,
"fbp" =>$fbc,
"fn" => $fn,
"ct" => $ct,
"st" => $st,
"zp" => $zp,
"country" => $country,
"external_id" => $email
),
"contents" => $items,
// "id" => $item_ids,
// "quantity" => count($item_qty),
// // "delivery_category"=> "home_delivery",
// "order_id" => $order_id
// ),
"custom_data" => array(
"currency" => "GBP",
"value" => $order_total,
),
"action_source" => "website",
"event_source_url" => $fullURL,
),
)
);
But my $item array look like this when I echo
{
"id": 814,
"order_id": 36956,
"name": "Pearson BTEC Level 7 Certificate in Strategic Management and Leadership (RQF)",
"product_id": 19555,
"variation_id": 0,
"quantity": 2,
"tax_class": "",
"subtotal": "1158",
"subtotal_tax": "0",
"total": "1158",
"total_tax": "0",
"taxes": {
"total": [],
"subtotal": []
},
"meta_data": []
},
{
"id": 815,
"order_id": 36956,
"name": "Pearson BTEC Level 7 Diploma in Strategic Management and Leadership (RQF)",
"product_id": 19107,
"variation_id": 0,
"quantity": 1,
"tax_class": "",
"subtotal": "999",
"subtotal_tax": "0",
"total": "999",
"total_tax": "0",
"taxes": {
"total": [],
"subtotal": []
},
"meta_data": []
}
And when I assign this $items and converted to json then I can see only the ides of the array
"user_data": {
"client_ip_address": "2402:d000:a200:a4a8:f06d:40a:cf85:e26d",
"client_user_agent": "",
"em": "b99526fedef7fe1da29e27d6f09cb64efew536978778e6cde3d8277d71a04398d1a4",
"ph": "db80005a39b11372054b7708cac76gsaaww47af6ed3fe4b37b9a8b2be435e2fcff04a7",
"fbc": "",
"fbp": "",
"fn": "83cd072a16ddb3d793c2f5bcd7d0basdree5a04af680279cf6a26fb8dffe57ce3b51a",
"ct": "17a0730b80e55f4bee9569be3f7e6d0wqw500c5568ecb8d785759d7151ef40f5bbd",
"st": "e3b0c44298fc1c149afbf4c8996fb9sas2427ae41e4649b934ca495991b7852b855",
"zp": "ac7bb74de6884ffce919c15fef4193749sdsd4588026c643973946713ac46da540d",
"country": "c820736841e811c96d30b14eb998feb6bsddc2c9d0764b7731267438dc7d6bb5b59",
"external_id": "b99526fedef7fe1da29e27d6f09ssscb64536978778e6cde3d8277d71a04398d1a4"
},
"contents": [
{
"814": {},
"815": {}
}
],
result should be look like this in this way in "centents" element
"contents" : [{'id':'ABC123','quantity' :2,'item_price':5.99}, {'id':'XYZ789','quantity':2, 'item_price':9.99, 'delivery_category': 'in_store'}]
I think the problem is that your $items, is actually an array of "strings" (json)
try to do a json_decode() on those $items before adding it to the content.
anyway, when you ask a question try to remove all unnecessary stuff, and make an example with the minimum code you need help with, in this case it takes a lot of reading through stuff just to understand the issue.

Group rows of data by a column value and restructure into an associative multi-dimensionsl array

I am trying to change an indexed array of arrays into a new array structure. My data is as follows:
$arr = array(
array( "year" => 1921, "name" => "bob" ),
array( "year" => 1944, "name" => "steve" ),
array( "year" => 1944, "name" => "doug" ),
array( "year" => 1921, "name" => "jim" ),
);
I would like to recreate a new array thats groups them into the same year. The best I can come up with is designating the year as the key so any row that has that year gets added to that key, but it's not the output that I'm looking for. What I need is how it's listed below.
"data": [
{
"year":"1921",
"names": [
{ "name":"bob" }, { "name":"jim"}
]
},
{
"year":1944",
"names": [
{ "name":"steve" }, { "name":"doug "}
]
}
You don't need to pre-extract the unique years nor use conditions within nested loops. Just push the data into the result set using temporary first-level keys, then remove the temporary keys when finished looping.
This ensures unique years, but allows names to be duplicated.
Code: (Demo)
$arr = [
["year" => 1921, "name" => "bob"],
["year" => 1944, "name" => "steve"],
["year" => 1944, "name" => "doug"],
["year" => 1921, "name" => "jim"],
];
foreach ($arr as $item) {
$result[$item['year']]['year'] = $item['year'];
$result[$item['year']]['names'][] = ['name' => $item['name']];
}
echo json_encode(
['data' => array_values($result)],
JSON_PRETTY_PRINT // for better visualization
);
Output:
{
"data": [
{
"year": 1921,
"names": [
{
"name": "bob"
},
{
"name": "jim"
}
]
},
{
"year": 1944,
"names": [
{
"name": "steve"
},
{
"name": "doug"
}
]
}
]
}

Create and fill an associative array of multiples dimensions

I'm currently trying to create an associative array which will have two dimensions and I think a solution for this probleme could resolve problemes for array with more dimensions.
I recover data with an API which look like that :
{
"item_id": "89",
"name": "Confiture de Myrtilles",
"product_id": "737",
"meta_key": "vmm_warehouse_sg_10783",
"meta_value": "0"
},
{
"item_id": "89",
"name": "Confiture de Myrtilles",
"product_id": "737",
"meta_key": "vmm_warehouse_sg_10782",
"meta_value": "0"
},
{
"item_id": "91",
"name": "Poires Guyot (bio)",
"product_id": "690",
"meta_key": "_backorders",
"meta_value": "no"
},
{
"item_id": "91",
"name": "Poires Guyot (bio)",
"product_id": "690",
"meta_key": "_sold_individually",
"meta_value": "no"
},
I just want to create an array like this :
array[item_id->[meta_key->meta_value]]
So I have to recover the item_id which will have the role of the secondth array and after put in this array the meta_key and meta_value associated.
So for example I will have an array like this :
Products[89]["vmm_warehouse_sg_10783"->"0"
"vmm_warehouse_sg_10782"->"0"]
And an other like this :
Products[91][........]
At the end, I will have a final array like this :
Products [ [89]->{"vmm_warehouse_sg_10783"->"0","vmm_warehouse_sg_10782"->"0"}
[91]->{.....}]
I have already tried something but I'm just a beginner and I don't found solution for my problem.
$Products = $this->wpdb->get_results( $SQL_Deliveries );
//this line allow $Products to recover all data from the API
foreach ( $Products as $Product ) {
$Meta_products[] = Product->item_id;
foreach($Product as $Product_meta){
$Meta_products[$item_id]->{Product_meta->meta_key,Product_meta
->meta_value);
}
I'm sure I did mitakes in my code too, but I really don't know how to resolve this problem. Thank you for your participation !
It looks like you want a multidimensional object array.
There is a little bit of fiddling involved to declare nested objects. The curly bracing is also necessary.
Code: (Demo)
$products = [
(object)["item_id" => "89",
"name" => "Confiture de Myrtilles",
"product_id" => "737",
"meta_key" => "vmm_warehouse_sg_10783",
"meta_value" => "0"
],
(object)["item_id" => "89",
"name" => "Confiture de Myrtilles",
"product_id" => "737",
"meta_key" => "vmm_warehouse_sg_10782",
"meta_value" => "0"
]
];
$result = (object)[];
foreach($products as $product) {
if (!isset($result->{$product->item_id})) {
$result->{$product->item_id} = (object)[];
}
$result->{$product->item_id}->{$product->meta_key} = $product->meta_value;
}
var_export($result);
Output:
(object) array(
'89' =>
(object) array(
'vmm_warehouse_sg_10783' => '0',
'vmm_warehouse_sg_10782' => '0',
),
)
Alternatively, to generate the nested object structure, you could build an array of arrays, then use json_encode(), then json_decode() on the result.
If you want an array as output, that's easiest:
Code: (Demo)
$products = [
(object)["item_id" => "89",
"name" => "Confiture de Myrtilles",
"product_id" => "737",
"meta_key" => "vmm_warehouse_sg_10783",
"meta_value" => "0"
],
(object)["item_id" => "89",
"name" => "Confiture de Myrtilles",
"product_id" => "737",
"meta_key" => "vmm_warehouse_sg_10782",
"meta_value" => "0"
],
(object)["item_id" => "91",
"name" => "Poires Guyot (bio)",
"product_id" => "690",
"meta_key" => "_backorders",
"meta_value" => "no"
],
(object)["item_id" => "91",
"name" => "Poires Guyot (bio)",
"product_id" => "690",
"meta_key" => "_sold_individually",
"meta_value" => "no"
]
];
$result = [];
foreach($products as $product) {
$result[$product->item_id][$product->meta_key] = $product->meta_value;
}
var_export($result);
Output:
array (
89 =>
array (
'vmm_warehouse_sg_10783' => '0',
'vmm_warehouse_sg_10782' => '0',
),
91 =>
array (
'_backorders' => 'no',
'_sold_individually' => 'no',
),
)
I don't fully understand what are you trying to achieve, but I suppose you want associative array with id as the key and array of meta_key and meta_value as its value?
If so, then:
foreach ( $Products as $Product ) {
$Meta_products[$Product->item_id][$Product->meta_key] = $Product->meta_value;
}

set a custom multiselect via JIRA REST API

I'm trying to set a custom field of type Multiselect via JIRA rest API using php. For reason I'm getting the following error:
{"errorMessages":[],"errors":{"Functionality Impacted":"expected 'value' property to be a string"}}
I have the following code for setting the custom field:
public function requestRemedy($summary, $description, $priority, $goliveDate,$startTime,
$endTime,$clientImpact,$impactedFunctionality,$fundTransfers ,$fieldAffected, $remedyChangeType,
$changeReason,$remedyImpact, $urgency,$riskLevel,$nameRequestor,$emailRequestor)
{
$json = Array ( "fields" => Array (
"project" => Array
( "id" => 10051 ),
"summary" => $summary,
"description" =>$description,
"issuetype" => Array ( "name" => "Remedy Change Management" ),
"priority" => Array("id" => $priority),
"customfield_13774" => $goliveDate,
"customfield_14408" => "$startTime",
"customfield_14409" => "$endTime",
"customfield_14412" => "$clientImpact",
"customfield_14908" =>Array ( 0 => Array(
"value" => ($impactedFunctionality),
)),
"customfield_14414" => Array("id" =>$fundTransfers),
// "customfield_14415" =>Array("id" => $businessOnline,"child" =>Array("id" => $businessDependency) ),
"customfield_14602" => Array("id" =>$fieldAffected),
"customfield_14422" => Array("id" =>$remedyChangeType),
"customfield_14423" => Array("id" =>$changeReason),
"customfield_14424" => Array("id" =>$remedyImpact),
"customfield_14425" => Array("id" =>$urgency),
"customfield_14426" => Array("id" =>$riskLevel),
"customfield_14700"=>$nameRequestor,
"customfield_14702"=>$emailRequestor
)
);
return $json;
}
After adding some dummy data to test the final structure of json, I get the following result:
{
"fields": {
"project": {
"id": 10051
},
"summary": "Test",
"description": "Human DeSC",
"issuetype": {
"name": "Remedy Change Management"
},
"priority": {
"id": "2"
},
"customfield_13774": "2016-11-08",
"customfield_14408": "2016-11-01T07:35:00.000+0200",
"customfield_14409": "2016-11-01T08:35:00.000+0200",
"customfield_14412": "cLIENT iMPACT",
"customfield_14908": [{
"value": ["Savings Accounts", "Current Accounts", "Call Deposits"]
}],
"customfield_14414": {
"id": "13647"
},
"customfield_14602": {
"id": "14022"
},
"customfield_14422": {
"id": "13712"
},
"customfield_14423": {
"id": "13718"
},
"customfield_14424": {
"id": "13722"
},
"customfield_14425": {
"id": "13726"
},
"customfield_14426": {
"id": "13730"
},
"customfield_14700": "Pastor Dan",
"customfield_14702": "email#time.com"
}
}
Which means the issue is here:
"customfield_14908": [{
"value": ["Savings Accounts", "Current Accounts", "Call Deposits"]
}],
the expected structure is:
"customfield_10008": [ {"value": "Savings Accounts" }, {"value": "Current Accounts" }, {"value": "Call Deposits" }]
Now I'm not sure how to build this using an associative array
The custom field I'm trying to set is customfield_14908. What I'm finding weird is that I used similar code for setting a multiselect field on JIRA version 7.2.1 and it works well, but not working on JIRA version 7.0.

Categories