Laravel - array to string with 2 fields - php

$warehouses = [
{
"id": 1,
"name": "warehouse 1",
"pivot": {
"product_id": "1",
"warehouse_id": 1,
"qty": 136.5
}
},
{
"id": 2,
"name": "warehouse 2",
"pivot": {
"product_id": "1",
"warehouse_id": 2,
"qty": 71.5
}
}
]
I need result like below.
$result = ["warehouse 1 - 136.5", "warehouse 2 - 71.5"];
plz help

$result = [];
foreach($warehouses as $i){
$result[] = $i['name'] . ' - ' . $i['pivot']['qty'];
}

Related

filtering json data in php laravel

I've a sample json data
"regions": [
{
"id": 1,
"name": "Region 1",
"state_id": 1,
"areas" :[ {
"id": 1,
"name": "area 1",
"region_id": 1},
{
"id": 2,
"name": "area 2",
"region_id": 1}
]
},
{
"id": 2,
"name": "Region 2",
"state_id": 1,
"areas" :[ {
"id": 3,
"name": "area 3",
"region_id": 2},
{
"id": 4,
"name": "area 4",
"region_id": 2}
]
}
]
How can I filter out the data the based on id in the regions? For example, if id is 2, then the response should be like
"regions": [
{
"id": 2,
"name": "Region 2",
"state_id": 1,
"areas" :[ {
"id": 3,
"name": "area 3",
"region_id": 2},
{
"id": 4,
"name": "area 4",
"region_id": 2}
]
}
]
You can json_decode that json string and then use array_filter method to filter regions
$regions = json_decode('{"regions":
[
{
"id": 1,
"name": "Region 1",
"state_id": 1,
"areas" :[ {
"id": 1,
"name": "area 1",
"region_id": 1
},{
"id": 2,
"name": "area 2",
"region_id": 1
}]
},{
"id": 2,
"name": "Region 2",
"state_id": 1,
"areas" :[{
"id": 3,
"name": "area 3",
"region_id": 2
},{
"id": 4,
"name": "area 4",
"region_id": 2
}]
}
]
}', true);
// Filter Region
$region_id = 2;
$filtered_regions = array_filter($regions['regions'], function($r) use ($region_id) {
return $r['id'] == $region_id;
});
// Filter By Area Id
$area_id = 2;
$filtered_areas = array_filter($regions['regions'], function($r) use ($area_id) {
$areas = array_filter($r['areas'], function($area) use ($area_id) {
return $area['id'] == $area_id;
});
return count($areas) > 0;
});
return ['regions' => $filtered_regions];
First apply json_decode on your json data then apply filter . If you want to get an whole object from this response array , then write a function which will accept the id and return that object after filtering.

Is it possible to edit the elements of a json array to accomodate additional data/elements?

I'm retrieving data from a database and pushing it to arrays then use json_encode() to output in json format. I have ended up having the data in this format.
[
{
"category_id": "1",
"category_name": "Construction Materials"
},
{
"items": [
{
"id": "1",
"item_name": "Wire Mesh",
"price": "459",
"image_url": null
},
{
"id": "2",
"item_name": "Cement",
"price": "700",
"image_url": null
},
{
"id": "3",
"item_name": "Barbed Wire",
"price": "3000",
"image_url": null
},
{
"id": "4",
"item_name": "Iron sheet",
"price": "200",
"image_url": null
}
]
},
{
"category_id": "2",
"category_name": "Plumbing"
},
Here is what I want to achieve:
[
{
"category_id": "1",
"category_name": "Construction Materials"
"items": [
{
"id": "1",
"item_name": "Wire Mesh",
"price": "459",
"image_url": null
},
{
"id": "2",
"item_name": "Cement",
"price": "40",
"image_url": null
},
{
"id": "3",
"item_name": "Barbed Wire",
"price": "3000",
"image_url": null
},
{
"id": "4",
"item_name": "Iron sheet",
"price": "200",
"image_url": null
}
]
},
{
"category_id": "2",
"category_name": "Plumbing"
},
How can I achive this in php. Is it possible to edit the contents of the main array? how can I add "items" after "category_name"
Regards..
$array = json_decode($yourJson);
$arrayLength = count($array);
$finalArray = [];
for ($i=0; $i < $arrayLength; $i+=2) {
$finalArray[] = $array[$i] + $array[$i + 1];
}
$backToJson = json_encode($finalArray);
Alternative to Mattijs's answer.
function get_first_property($object) {
$properties = array_keys(get_object_vars($object));
return reset($properties);
}
function object_merge($object1, $object2) {
return (object) array_merge((array) $object1, (array) $object2);
}
// loop through each of the array objects
$previous_first_property = null;
foreach ($array as $i => $object) {
$first_property = get_first_property($object);
// merge if the 1st property is "items", and the previous 1st was "category_id"
if ($first_property == "items" && $previous_first_property == "category_id") {
$array[$i - 1] = object_merge($array[$i - 1], $array[$i]);
unset($array[$i]);
}
$previous_first_property = $first_property;
}

Laravel : How do I return parent > child relationship from same table

I have a 3 tables product, category, attributes. In attributes table there is parent_id used for sub-attributes in a same table.Using loop I get a data.
My code :
$productDetails = Product::with('categories')->get();
foreach ($productDetails as $key => $value) {
foreach ($value->categories as $key => $value) {
$attributes = Attribute::where('product_id',$value->product_id)->where('category_id',$value->id)->where('parent_id',Null)->get();
$value->Attributes = $attributes;
foreach ($attributes as $key => $value) {
$subAttributes = Attribute::where('parent_id', $value->id)->get();
$value->subAttributes = $subAttributes;
}
}
}
Output :
{
"productDetails": [
{
"id": 1,
"title": "Small Size Diamond",
"icon": null,
"status": "Active",
"categories": [
{
"id": 1,
"product_id": 1,
"title": "Sieve Size",
"status": "Active",
"sort_order": 1,
"Attributes": [
{
"id": 1,
"product_id": 1,
"category_id": 1,
"parent_id": null,
"title": "- 2.0",
"status": "Active",
"sort_order": 1,
"subAttributes": [
[
{
"id": 9,
"product_id": 1,
"category_id": 1,
"parent_id": 1, // Attributes table ID
"title": "+ 0000 - 000",
"status": "Active",
"sort_order": 1
},
{
"id": 10,
"product_id": 1,
"category_id": 1,
"parent_id": 1, // Attributes table ID
"title": "+ 000 - 00",
"status": "Active",
"sort_order": 2
}
]
]
}
]
}
]
}
]}
The problem is in first product I gt completed response but in other prodcts in loop I do not get subAttributes data. How can i do this?
Simple, please do not use same variable name in all foreach loop,
Your code should like following
$productDetails = Product::with('categories')->get();
foreach ($productDetails as $pro_key => $pro_value) {
foreach ($pro_value->categories as $cat_key => $cat_value) {
$attributes = Attribute::where('product_id',$cat_value->product_id)->where('category_id',$cat_value->id)->where('parent_id',Null)->get();
$cat_value->Attributes = $attributes;
foreach ($attributes as $att_key => $att_value) {
$subAttributes = Attribute::where('parent_id', $att_value->id)->get();
$att_value->subAttributes = $subAttributes;
}
}
}

Presenting MYSQL nested JSON object with php

I have a MYSQL Table stored using 000webhostapp cpanel, here is what it look like.
id | name | J_Object
---------------------------------------------------------
1 | deckA | {"type":"A", "ports": {"hdmi": 1, "usb":2}}
2 | deckB | {"type":"B", "ports": {"hdmi": 3, "usb":2}}
3 | deckC | {"type":"A", "ports": {"hdmi": 1, "usb":2}}
4 | deckD | {"type":"B", "ports": {"hdmi": 3, "usb":2}}
Using PHP, I would like to present it like the below to act as a HTTP to pass the data to other platforms.
[
{
"id": "1",
"name": "deckA",
"J_Object": [{"type":"A", "ports": {"hdmi": 1, "usb":2}}]
},
{
"id": "2",
"name": "deckB",
"J_Object": [{"type":"B", "ports": {"hdmi": 3, "usb":2}}]
},
{
"id": "1",
"name": "deckC",
"J_Object": [{"type":"A", "ports": {"hdmi": 1, "usb":2}}]
},
{
"id": "1",
"name": "deckD",
"J_Object": [{"type":"B", "ports": {"hdmi": 3, "usb":2}}]
}
]
However, with my PHP I written below, what follows after is what I got. And it is definitely not what I wanted.
The PHP code:
$search = "SELECT * FROM `database`.`products`
WHERE JSON_EXTRACT(`J_Object` , '$.ports.usb') > 2
AND JSON_EXTRACT(`J_Object` , '$.ports.hdmi') > 1;";
$result = mysqli_query($link, $search);
if ($result) {
//Printing out the details of the rows
while($array = mysqli_fetch_assoc($result)) {
$jsonData[]=$array;
}
$nonArr = json_encode($jsonData, JSON_PRETTY_PRINT);
$stringArr = (string)$nonArr;
$nonSlash = str_replace("\\","", $stringArr);
echo $nonSlash;
}
mysqli_close($link)
And the below is the unwanted results:
[
{
"id": "1",
"name": "deckA",
"J_Object": "{"type":"A", "ports": {"hdmi": 1, "usb":2}}"
},
{
"id": "2",
"name": "deckB",
"J_Object": "{"type":"B", "ports": {"hdmi": 3, "usb":2}}'
},
{
"id": "1",
"name": "deckC",
"J_Object": "{"type":"A", "ports": {"hdmi": 1, "usb":2}}"
},
{
"id": "1",
"name": "deckD",
"J_Object": "{"type":"B", "ports": {"hdmi": 3, "usb":2}}"
}
]
It looks like its the same but if you notice the [ ] is changed with " " which also means that the nested object is not quite right.
Can any pro out there show me how do I get the correct output?
You could try a much simpler way.
$result = mysqli_query($link, $search);
if ($result) {
//Printing out the details of the rows
while($array = mysqli_fetch_assoc($result)) {
$array['J_Object'] = [json_decode($array['J_Object'], true)];
$jsonData[]=$array;
}
echo json_encode($jsonData, JSON_PRETTY_PRINT);
}
This would work for you. It's just a quick fix with preg_replace.
$result = mysqli_query($link, $search);
if ($result) {
//Printing out the details of the rows
while($array = mysqli_fetch_assoc($result)) {
$jsonData[]=$array;
}
$nonArr = json_encode($jsonData, JSON_PRETTY_PRINT);
$stringArr = (string)$nonArr;
$nonSlash = str_replace("\\","", $stringArr);
// quick fix
$nonSlash = preg_replace("/[\"]{1}[{]{1}/", '[{', $nonSlash);
$nonSlash = preg_replace("/[}]{1}[\"]{1}/", '}]', $nonSlash);
echo $nonSlash;
}
Output:
[
{
"id": "1",
"name": "deckA",
"J_Object": [{"type":"A", "ports": {"hdmi": 1, "usb":2}}]
},
{
"id": "2",
"name": "deckB",
"J_Object": [{"type":"B", "ports": {"hdmi": 3, "usb":2}}]
},
{
"id": "3",
"name": "deckC",
"J_Object": [{"type":"A", "ports": {"hdmi": 1, "usb":2}}]
},
{
"id": "4",
"name": "deckD",
"J_Object": [{"type":"B", "ports": {"hdmi": 3, "usb":2}}]
}
]
Hope you find this helpful. Happy coding..

Structure JSON output with PHP

I am trying to generate a JSON output from the DATABASE with MySQL.
The result that I want is that I want an array around two matching ID's found in the tabel in the database.
To visualise what I wish to achieve here is my code:
This is my query
$sql = "SELECT * FROM `flower_garden` WHERE `id_flower` IN (0, 1)";
$result = mysql_query($sql);
while($record = mysql_fetch_assoc($result)) {
$rows[] = $record;
}
print json_encode($rows);
This is the JSON result I wish to achieve:
(What I want)
[
[
"id": "1",
"id_flower": "3",
"Title": "rose",
"Price": 1.25,
"Number": 15
},
{
"id": "2",
"id_flower": "3",
"Title": "daisy",
"Price": 0.75,
"Number": 25
}
],
[
{
"id": "3",
"id_flower": "6",
"Title": "rose",
"Price": 1.25,
"Number": 15
},
{
"id": "4",
"id_flower": "6",
"Title": "daisy",
"Price": 0.75,
"Number": 25
}
]
]
Visual result:
So, I want the matching ID's (in this case id_flower) put in one array.
This is the result I get:
(What I get)
[
[
"id": "1",
"id_flower": "3",
"Title": "rose",
"Price": 1.25,
"Number": 15
},
{
"id": "2",
"id_flower": "3",
"Title": "daisy",
"Price": 0.75,
"Number": 25
},
{
"id": "3",
"id_flower": "6",
"Title": "rose",
"Price": 1.25,
"Number": 15
},
{
"id": "4",
"id_flower": "6",
"Title": "daisy",
"Price": 0.75,
"Number": 25
}
]
]
Visual result:
Try this
foreach ($rows as $key => $val) {
$return[$val['id_flower']][] = $val;
}
echo json_encode($return);
Please note I have not tested it.
$sql = "SELECT * FROM `flower_garden` WHERE `id_flower` IN (0, 1)";
$result = mysql_query($sql);
$rows = array();
while($record = mysql_fetch_assoc($result)) {
array_push($rows[$record["id_flower"]], $record);
}
$result = array();
foreach($rows as $k => $v){
array_push($result, $v);
}
echo json_encode($result);
test yourself !

Categories