Error with dynamic json array in php - php

I have an application that retrieves data from a mysql database and generates a json output with php to send to a plugin.
I'm generating the following json output from php:
{
"mapwidth":"1300",
"mapheight":"1000",
"categories":"[]",
"levels":{
"id":"lots",
"title":"Lots",
"map":"maps\/lot-map.svg",
"minimap":"",
"locations":[
{
"id":"lot1",
"title":"Lot 1",
"pin":"hidden",
"description":"<p>Status: <b style=\\\"color: #8eba5e;\\\">Available<\/b><br>Size:\u00a0<b>850 sqm<\/b><br>Please get in touch for an Offer.<\/p>",
"link":null,
"x":"0.4849",
"y":"0.4629",
"fill":null,
"category":"false",
"action":"tooltip"
}
]
},
"maxscale":"1.8"
}
But the format is incorrect. Should be like the following tested json file:
{
"mapwidth": "1300",
"mapheight": "1000",
"categories": [],
"levels": [
{
"id": "lots",
"title": "Lots",
"map": "maps/lot-map.svg",
"minimap": "",
"locations": [
{
"id": "lot12",
"title": "Lot 12",
"pin": "hidden",
"description": "<p>Status: <b style=\"color: #8eba5e;\">Available</b><br>Size: <b>850 sqm</b><br>Please get in touch for an Offer.</p>",
"link": "#more",
"x": "0.3726",
"y": "0.4565"
}
]
}
],
"maxscale": 1.8
}
The difference is in the "levels" key.
This is my php code:
$results = array(
'mapwidth' => '1300',
'mapheight' => '1000',
'categories' => '[]'
);
$results['levels'] = array(
'id' => 'lots',
'title' => 'Lots',
'map' => 'maps/lot-map.svg',
'minimap' => ''
);
if ($lotes)
{
// build usable array
foreach($lotes['results'] as $lote)
{
$results['levels']['locations'][] = array(
'id' => $lote['slug'],
'title' => $lote['title'],
'pin' => $lote['pin'],
'description' => $lote['description'],
'link' => $lote['link'],
'x' => $lote['position_x'],
'y' => $lote['position_y'],
'fill' => $lote['fill'],
'category' => $lote['category'],
'action' => $lote['action']
);
}
}
else
$results['error'] = lang('core error no_results');
$results['maxscale'] = '1.8';
// display results using the JSON formatter helper
display_json($results);
Any suggestions? Thanks

You need to make the levels a multidimensional array.
$results['levels'] = array();
$results['levels'][0] = array(
'id' => 'lots',
'title' => 'Lots',
'map' => 'maps/lot-map.svg',
'minimap' => ''
);
Then when you append to do, do it as follows:
$results['levels'][0]['locations'][] = array(

Related

Loop through Categories and its Products in PHP Laravel

I have to create an array with the categories array and its related products i'm fetching category with all related products using this query
$categoryData= Category::with('product')->get();
Data is beign fetched properly, using this loop to get data in the format given below:
foreach($categoryData as $row){
$categoriesData[] = [
'id' => $row->id,
'title' => $row->title,
];
foreach($row->product as $rowproduct){
$categoriesData['product_details'][] = [
'product_name' => $rowproduct->name,
'product_price' => $rowproduct->price
];
}
}
Format (It should be something like this) :
{
"categoriesData": {
"0": {
"id": 1,
"category_name" : "Name 1",
"product_details": [
{
"id": 1,
"product_name": Product Name,
},
],
"1": {
"id": 2,
""category_name" ": "Name 2",
"product_details": [
{
"id": 1,
"product_name": product name,
},
},
but through present loop all product is getting saved in one array. It is not saving inside category.
Any help is highly appreciated
You can do this with Collection methods if you wanted to, basically just map:
$array = $categoryData->map(function ($category) {
return [
'id' => $category->id,
'title' => $category->title,
'product_details' => $category->products->map(function ($product) {
return [
'product_name' => $product->name,
'product_price' => $product->price,
];
}),
];
})->all();
Though this is going in the direction of using a transformer or API resource to format this data.
Hi I think this is what you're looking for :
foreach ($categoryData as $key => $row) {
$categoriesData[$key] = [
'id' => $row->id,
'title' => $row->title,
];
foreach ($row->product as $rowproduct) {
$categoriesData[$key]['product_details'][] = [
'product_name' => $rowproduct->name,
'product_price' => $rowproduct->price
];
}
}

Json starting with [ and when using json_encode it starts with " in magento2 using php7.1

I want my json to start with { but if using json_encode it is getting converted into string, I am using php7.1 on ubuntu and working on magento 2.3
This is what I am getting with the below code, I don't want '['
[
{
"success": "true",
"data": {
"mainimages": [
{
Here is my code
$response = array(
array(
"success" => "true",
"data" => $alldata,
"newarrivalheading" => "NEW ARRIVALS",
"instagramheading" => "CELEBS IN LULU",
"specialpriceheading" => "SPECIAL PRICES",
"editorwishlistheading" => "EDITOR'S WISHLIST",
"stylehighlightheading" => "STYLE HIGHLIGHTS",
"styletagline" => "#Looks to swipe right",
"newarrivalindex" => 3,
"instagramindex" => 9,
"editorwishlistviewall" => "",
"sliderimage" => $sliderimage
)
);
return $response;
This is what I want
{
"success": "true",
"data": {
"mainimages": [
{
So remove the unnecessary outer array like so
$alldata = [1,2,3,4];
$sliderimage = ['xz.jpg','ab.png'];
$response = array(
"success" => "true",
"data" => $alldata,
"newarrivalheading" => "NEW ARRIVALS",
"instagramheading" => "CELEBS IN LULU",
"specialpriceheading" => "SPECIAL PRICES",
"editorwishlistheading" => "EDITOR'S WISHLIST",
"stylehighlightheading" => "STYLE HIGHLIGHTS",
"styletagline" => "#Looks to swipe right",
"newarrivalindex" => 3,
"instagramindex" => 9,
"editorwishlistviewall" => "",
"sliderimage" => $sliderimage
);
echo json_encode($response);
RESULT
{
"success": "true",
"data": [
1,
2,
3,
4
],
"newarrivalheading": "NEW ARRIVALS",
"instagramheading": "CELEBS IN LULU",
"specialpriceheading": "SPECIAL PRICES",
"editorwishlistheading": "EDITOR'S WISHLIST",
"stylehighlightheading": "STYLE HIGHLIGHTS",
"styletagline": "#Looks to swipe right",
"newarrivalindex": 3,
"instagramindex": 9,
"editorwishlistviewall": "",
"sliderimage": [
"xz.jpg",
"ab.png"
]
}

php - How to insert a foreach loop inside a multidimensional array

How to insert a foreach loop inside a multidimensional array ?
I have a multidimensional array that I use to connect my website to Mailchimp. I have to check with a foreach loop the number of products that the user buys, and add these insiede a array call "lines".
This is at moment my json code, that after I will send to Mailchimp:
$json_data = '{
"id": "2'. $order->id .'",
"customer": {
"id": "71",
"email_address": "'.$order->email.'",
"opt_in_status": true,
"company": "'.$order->company_name.'",
"first_name": "'.$order->pad_firstname.'",
"last_name": "'.$order->pad_lastname.'",
"orders_count": 1,
"total_spent": 86
},
"checkout_url": "https://www.mywebsite.it/en/checkout/confirmation/",
"currency_code": "EUR",
"order_total": 86,
"lines"[{
'.$line_result.'
}]
}';
The $line_result is where I try to add the array of the products.
I know is wrong.
all the array inside the "lines" need be like this:
"lines":[
{
data product 1 ...
},
{
data product 2 ...
}
]
This is my foreach:
foreach ($order->pad_products as $product) {
$line_result['line'] = array(
"id" => "$order->id",
"product_id" => "$product->pad_product_id",
"product_title" => "$product->title",
"product_variant_id" => "$product->id",
"product_variant_title" => "$product->title",
"quantity" => "$product->pad_quantity",
"price" => "$product->prezzo",
);
};
what is the correct way to insert this data and create a multidimensional array like the one I need?
Thank you.
You just need to store all $line_result in global variable, and then, bind it to your json model :
$results = [];
foreach ($order->pad_products as $product) {
$results[] = array(
"id" => $order->id,
"product_id" => $product->pad_product_id,
"product_title" => $product->title,
"product_variant_id" => $product->id,
"product_variant_title" => $product->title,
"quantity" => $product->pad_quantity,
"price" => $product->prezzo,
);
};
$data = json_decode($json_data, true);
$data['lines'] = $results;
$json = json_encode($data);
EDIT : Script array to json
$lines = [];
foreach ($order->pad_products as $product) {
$lines[] = array(
"id" => $order->id,
"product_id" => $product->pad_product_id,
"product_title" => $product->title,
"product_variant_id" => $product->id,
"product_variant_title" => $product->title,
"quantity" => $product->pad_quantity,
"price" => $product->prezzo,
);
}
$data = [
'id' => '2'.$order->id,
'customer' => [
'id' => '71',
'email_address' => $order->email,
'opt_in_status' => true,
'company' => $order->company_name,
'first_name' => $order->pad_firstname,
'last_name' => $order->pad_lastname,
'orders_count' => 1,
'total_spent' => 86
],
'checkout_url' => 'https://www.mywebsite.it/en/checkout/confirmation',
'currency_code' => 'EUR',
'order_total' => 86,
'lines' => $lines
];
$jsonData = json_encode($data, JSON_UNESCAPED_UNICODE);
I want say thank you to #adrianRosi for the help and the input he gives me.
In the end I find my solution, that it's json_encode the array before add into $data in json format.
in this way:
$product_list = [];
foreach ($order->pad_products as $product) {
$product_list[] = array(
"id" => "$id",
"..." => "...",
);
};
$data_products['lines'] = $product_list;
$json_products = json_encode($data_products);
$json_products_edit = substr($json_products, 1, -1); // to delete the {}
$prezzo_totale = $order->pad_price_total;
$json_data = '{
...
...
'.$json_products_edit.'
}';

Elasticsearch Sort based on value first

I want to sort results on the release date. I want 2015 movies first and the rest of the years sorted on the has_poster value. So I get results like:
2015, 2015, 1989, 2017, 2006
etc.
So far this is what I've got.
$params['index'] = 'movies';
$params['type'] = 'movie';
$params['body']['size'] = 50;
$params['body']['sort'] = array(
array('has_poster' => "desc"),
array('_score' => "desc"),
);
$params['body']['query']['filtered'] = array(
'query' => array(
'query_string' => array(
'query' => "survivor",
'fields' => array('name', 'orig_title'),
'default_operator' => "AND"
),
)
);
I need the equivalent of ... ORDER BY FIELD(releasedate, 2015), has_poster DESC ... in MySQL for Elasticsearch.
You need a scripted sorting:
{
"sort": [
{
"_script": {
"script": "if(doc['releasedate'].date.year==2015) return 1; else return 0;",
"type": "number",
"order": "desc"
}
},
{
"has_poster": "desc"
}
]
}
Im not work =>type name is string
$params['body']['sort']= array('name' => 'desc' );
or
$params=[
'index'=>'pets',
'type'=>'bird',
'body'=>[
'query'=>[
'bool'=>[
'must'=>[],
'filter'=>[
'range'=>[
'registered'=>[
'gte' => "2020-10-01",
'lte' => "2020-11-30"]
]
]
]
],
'sort'=>[
'name'=>[
'order'=>'asc'
]
]
]
];
but not work

php display only duplicate value from array (facebook api)

I want delete duplicate post from array of facebook graph data
my page data like :
{
"data": [
{
"link": "http://example.com/188",
"id": "427801497327797_428375477270399",
"created_time": "2013-06-29T14:16:26+0000"
},
{
"link": "http://example.com/188",
"id": "427801497327797_428375187270428",
"created_time": "2013-06-29T14:15:27+0000"
},
{
"link": "http://example.com/188",
"id": "427801497327797_428363873938226",
"created_time": "2013-06-29T13:33:17+0000"
},
{
"link": "http://example.com/196",
"id": "427801497327797_428363597271587",
"created_time": "2013-06-29T13:32:07+0000"
}
],
"paging": {
"previous": "",
"next": ""
}
}
You can see duplicate link example.com/188.
I want get id of all duplicate link.
I'm working with facebook-page-poster
If your concern is to remove duplicate link data then you can do like this
<?php
$duplicate_ids = array();
$all_links = array();
$facebook_data = array(
'data' => array(
array(
'link' => 'http=>//site.com/188',
'id' => '427801497327797_428375477270399',
'created_time' => '2013-06-29T14=>16=>26+0000'
), array(
'link' => 'http=>//site.com/188',
'id' => '427801497327797_428375187270428',
'created_time' => '2013-06-29T14=>15=>27+0000'
), array(
'link' => 'http=>//site.com/188',
'id' => '427801497327797_428363873938226',
'created_time' => '2013-06-29T13=>33=>17+0000'
), array(
'link' => 'http=>//site.com/196',
'id' => '427801497327797_428363597271587',
'created_time' => '2013-06-29T13=>32=>07+0000'
)
),
'paging' => array(
'previous' => '',
'next' => ''
)
);
$data_count = count($facebook_data['data']);
for ($i = 0; $i < $data_count; $i++) {
if (in_array($facebook_data['data'][$i]['link'], $all_links)) {
$duplicate_ids[] = $facebook_data['data'][$i]['id'];
unset($facebook_data['data'][$i]);
} else {
$all_links[] = $facebook_data['data'][$i]['link'];
}
}
echo '<pre>'; print_r($duplicate_ids); '</pre>';

Categories