I have return data like below json object,
{
"user_token": "ad48c412-3866-4ac9-adf6-3328911ae46c",
"order_info": {
"order_id": "CGC12345678",
"company_id": 32,
"price": 1000.5,
"currency": "MYR",
"products": [
{ "type": "hr_claims", "name": "HR Claims", "is_fixed_price": true, "price": 500.5, "currency": "MYR" },
{ "type": "hr_leave", "name": "HR Leave", "is_fixed_price": true, "price": 500, "currency": "MYR" },
{ "type": "finance_advisory", "name": "FinanceAdvisory", "is_fixed_price": false, "currency": "MYR" }
],
"total_invoices": 200,
"total_staffs": 80
}
}
i want to save this one object in php table one row but since products have 3 different array i cannot get all 3 [products][name] in to one record in php table.
Like below
products - HR Claims, HR Leave, Finance Advisory
Can someone help me?
This is i try! This one return last one!
<td>
#php
$json = $order->data;
$json = json_decode($json, true);
$products = $json['order_info']['products'];
foreach ($products as $hitsIndex => $hitsValue) {
$data = $hitsValue['name']. '<br/>';
}
#endphp
{{$data}}
</td>
In your foreach loop you overwrite $data on every iteration, that's why you only get the last entry. You need to concatenate your results to $data.
Change
foreach ($products as $hitsIndex => $hitsValue) {
$data = $hitsValue['name']. '<br />';
}
to
$data = '';
foreach ($products as $hitsIndex => $hitsValue) {
$data .= $hitsValue['name']. '<br />';
}
Related
This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 4 years ago.
I have this kind of json objects and im trying to search an item under sales->products->id but i can't make it work. I hope someone could help me. Thanks!
"sales": [
{
"ID": 123456,
"transaction_id": "123456789",
"key": "sdawa57sd547sad4sadx54ad",
"subtotal": 20,
"tax": "0",
"fees": null,
"total": "20",
"gateway": "paypal",
"email": "email#email.com",
"date": "2018-08-01 13:13:55",
"discounts": null,
"products": [
{
"id": 1234,
"quantity": 1,
"name": "Product 1",
"price": 20,
"price_name": ""
}
]
}
This is the code i used:
$content = file_get_contents($url);
$results= json_decode($content, TRUE);
foreach($results->sales as $item)
{
if($item->products->id == "1234")
{
echo $item->products->name;
}
}
Because you've passed the second parameter as true to json_decode, your $results variable is an array, so you need to access it like that:
foreach($results['sales'] as $item) {
foreach ($item['products'] as $product) {
if ($product['id'] == '1234') echo $product['name'];
}
}
Output:
Product 1
Demo on 3v4l.org
If you want to find which sales have the product, then you should do this
$results= json_decode($content);
$productid = "1234"; //product you want to search for
foreach($result->sales as $sale)
{
$keys = array_keys(array_column($sale->products, 'id'), $product_id);
if(!empty($keys))
$saleIDs[] = $sale->ID;
}
var_dump($saleIDs); //contains all the sale IDs that have the product
Read about array_keys and array_column.
I get an array in JSON format and I decode this data. I can access to single data by selecting e.g. echo $myArray[0]["name"];
However, I want to do a loop to iterate all names and prices from the array. Can you support me to find the bug in my code?
$url = "myurl";
$response = file_get_contents($url);
$myArray = json_decode($response, true);
foreach ($myArray as $product) {
echo $product->name . '<br>';
}
and here is a sample of the array:
[{
"id": 782,
"name": "Test Translation New",
"price": "1",
"image": {
"url": "xxx/image-2.jpg",
"position": 0
},
"link": "https:xxx",
"nickname": "newmarker"
}, {
"id": 777,
"name": "Test Translation",
"price": "0",
"image": {
"url": "https:xxx/image-1.jpg",
"position": 0
},
"link": "https:xxx",
"nickname": "newmarker"
}]
You are using json_decode(..., true), so the returned $myArray is an array, and all its sub items are all arrays.
<?php
$response = '
[{
"id": 782,
"name": "Test Translation New",
"price": "1",
"image": {
"url": "xxx/image-2.jpg",
"position": 0
},
"link": "https:xxx",
"nickname": "newmarker"
}, {
"id": 777,
"name": "Test Translation",
"price": "0",
"image": {
"url": "https:xxx/image-1.jpg",
"position": 0
},
"link": "https:xxx",
"nickname": "newmarker"
}]
';
$myArray = json_decode($response, true);
foreach ($myArray as $product) {
echo $product['name'] . "<br>\n";
}
Output:
Test Translation New<br>
Test Translation<br>
If the second argument of json_decode is given and it is true then the returned structure is an associative array. That being said you may print the names and prices like:
foreach ($myArray as $product) {
echo $product['name'] . ' - ' . $product['price'] . '<br>';
}
If the second argument of json_decode is given and it is true then the returned structure is an associative array. That being said you may print the names and prices like:
foreach ($myArray as $product) {
echo $product['name'];
echo (int) $product['price'];
}
or you can also do
foreach ($myArray as $product) {
echo "{$product['name']} - {$product['price']} <br />";
}
I'm trying to get orders from parse.com using PHP SDK. I have Order class in parse. And Order class has items column like this:
[
[
{
"id": "uXtRcVLQ3V",
"name": "Coca cola",
"price": 4,
"thumbnail": "https://parsefiles.back4app.com/taT6ySwwyza3B2MJucucqWz9pMqBZ00Pd7w7hoZf/e8e8d5ee1e5242a1acd759827df41473_pdp-coca-cola-hfcs-2l.png",
"category": {
"id": "cYqrWcCzkt",
"name": "İçecek"
},
"offer": true
},
1
],
[
{
"id": "DWzLluzSpb",
"name": "Darr",
"price": 12,
"thumbnail": "https://parsefiles.back4app.com/taT6ySwwyza3B2MJucucqWz9pMqBZ00Pd7w7hoZf/8d7c0eae7c74d269319fed0a4f4e50e7_bilisim-paylasimlari.jpg",
"category": {
"id": "bGVCMX79Y0",
"name": "Deterjan, Temizlik"
},
"offer": true
},
1
]
]
I want to get and echo name, price, thumbnail, category of each items in array using Parse PHP SDK.
The beginning of my PHP code is:
$query = new ParseQuery("Order");
$results = $query->find();
I've solved problem. I used nested foreach loop.
$query = new ParseQuery("Order");
$results = $query->find();
foreach($results as $obj) {
$items = $obj->get("items");
foreach($items as $prod) {
echo $prod[1] . " x " . $prod[0]["name"] . "<br>";
}
echo $obj->get("total");
}
I have a code that outputs the json result below:
{
"Ghost in the Shell": {
"id": 1203,
"Pipeline": {
"id": 6144,
"name": "Pipeline",
"status": "New",
"item_id": 5962,
"TotalTasksOpen": 2
}
}
}
Now how can I format it in the my desired json format below:
Note* I have to remove some result.
{
"Ghost in the Shell":
"id": 6144,
"name": "Pipeline",
"status": "New",
"item_id": 5962,
"TotalTasksOpen": 2
}
Will appreciate if anyone can help me please.
I am not sure what is your purpose , but here is what you need
<?php
$json = '{
"Ghost in the Shell": {
"id": 1203,
"Pipeline": {
"id": 6144,
"name": "Pipeline",
"status": "New",
"item_id": 5962,
"TotalTasksOpen": 2
}
}
}';
$array = json_decode($json, true);
$newArray = array();
foreach($array as $key=>$value) {
$newArray[$key] = '';
foreach($value as $k=>$v) {
if(is_array($v)) {
$newArray = array_merge($newArray,$v);
}
}
}
$newJson = json_encode($newArray);
echo $newJson;
?>
I have some json data that i am retrieving from an external url. It is not importing correctly unless i take out some of the brackets. Anyone know how to properly import this json data? I don't really need the "success", "num_items", "build time" and "updated at". Im a noobie. Thanks!
Here is the php
$filename = "http://www.someurl.com/data.json";
$data = file_get_contents($filename);
$array = json_decode($data, true);
foreach($array as $row)
{
$sql = "INSERT INTO table_all_items(name, quality) VALUES (
'".$row["name"]."',
'".$row["quality"]."'
)";
mysqli_query($connect, $sql);
}
Here is data.json
{
"success": true,
"num_items": 7312,
"items": [
{
"name": "Net",
"quality": "New"
},
{
"name": "Ball",
"quality": "New"
},
{
"name": "Hoop",
"quality": "Used"
}
],
"build_time": 320,
"updated_at": 15680
}
You were looping through the wrong element of your array.
As you want to list the items, your loop must look like :
foreach($array["items"] as $row)
//$filename = "http://www.someurl.com/data.json";
//$data = file_get_contents($filename);
$data='{
"success": true,
"num_items": 7312,
"items": [
{
"name": "Net",
"quality": "New"
},
{
"name": "Ball",
"quality": "New"
},
{
"name": "Hoop",
"quality": "Used"
}
],
"build_time": 320,
"updated_at": 15680
}';
$array = json_decode($data, true);
$sql = "INSERT INTO table_all_items(name, quality) VALUES ";
foreach($array["items"] as $row)
{
$sql = $sql." (
'".$row["name"]."',
'".$row["quality"]."'
),";
}
mysqli_query($connect, substr($sql,0,-1));
I also updated the sql query, for it sends only one request with many values, instead on many requests with one value.