Search item on json object PHP [duplicate] - php

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.

Related

How to iterate arrays nested in arrays [duplicate]

This question already has an answer here:
Loop through nested arrays PHP
(1 answer)
Closed 12 months ago.
I have the json array below and im trying to access the ProductResults bit.
I want the output to be somthing like this:
Term: 47, Type:HP, Payment: 229.4
Term: 47, Type:PCP, Payment: 172.23
Term: 60, Type:PCP, Payment: 186.82
But im struggeling to even access other parts of the array.
PHP:
$json = json_decode($resp, true);
foreach ($json['VehicleResults'] as $item)
{
$data = $item['FinanceProductResults'];
$v0 = $data['Term'];
echo $v0;
}
JSON:
{
"VehicleResults": [{
"Id": "0",
"FinanceProductResults": [{
"Term": 47,
"AnnualMileage": 6000,
"Deposits": 1000,
"ProductResults": [{
"Key": "HP",
"Payment": 229.4
}, {
"Key": "PCP",
"Payment": 172.23
}]
}, {
"Term": 60,
"AnnualMileage": 6000,
"Deposits": 1000,
"ProductResults": [{
"Key": "HP",
"Payment": 186.82
}]
}]
}]
}
The FinanceProductResults is also an array so it needs to be accessed also as an array. Like you have accessed VehicleResults and same goes for ProductResults. So your code should look something like this.
$json = json_decode($resp, true);
foreach ($json['VehicleResults'] as $item)
{
$dataItems = $item['FinanceProductResults'];
foreach ($dataItems as $data) {
$v0 = $data['Term'];
foreach ($data['ProductResults'] as $productResult) {
$type = $productResult['Key'];
$payment = $productResult['Payment'];
echo "Term: $v0, Type: $type, Payment: $payment";
}
}
}

Illegal string offset only when iterated as a set [duplicate]

This question already has answers here:
"Illegal offset" inside of loop [duplicate]
(2 answers)
PHP Warning - Illegal string offset
(1 answer)
Closed 1 year ago.
I know there are many other questions on this but my case is quite peculiar, my illegal offset only occurs when I iterate it with the others but is fine when I do it on its own.
I am using Slimframework.
My array looks like this:
{
"cart": {
"cartId": "9c7b7c3e-d4d3-4de1-afa4-f81e63b50906",
"orderNo": 1,
"orderType": "Collection",
"customerName": "",
"customerTel": "",
"address": "",
"items": [
{
"itemId": 2,
"itemName": "Item A",
"itemPrice": 5.75,
"qty": 1
},
{
"itemId": 1,
"itemName": "Item B",
"itemPrice": 5.25,
"qty": 1
},
{
"itemId": 4,
"itemName": "Item C",
"itemPrice": 9.3,
"qty": 1
},
{
"itemId": 3,
"itemName": "Item D",
"itemPrice": 8.6,
"qty": 1
}
]
},
"shopId": 1,
"discount": 0,
"total": "28.90",
"method": "Card"
}
When I do this in slimframework:
$order = $request->getParsedBody();
$this->response->withJson($order['cart']['items']);
It returns the exact same array moreover, if I check what is $order['cart']['items'][0]['itemPrice'] I get 5.75.
But when I iterate over it like:
foreach($order['cart']['items'] as $item)
{
$itemId = $item['itemId'];
$item = $item['itemName'];
$itemPrice = $item["itemPrice"];
$itemQty = $item["qty"];
}
I always get Illegal string offset 'itemPrice' & 'qty'.
I have also tried the below and it's not a problem:
$itemPrice;
foreach($order['cart']['items'] as $item)
{
$itemPrice .= $item["itemPrice"]
}
$this->response->withJson($itemPrice);
I might be missing something really obvious, any pointers would be highly appreciated.
You did override your loops $item variable with $item['itemName'];. From this point on your $item variable has no "itemPrice" nor "qty" keys, because it is scalar. You just need to change variable namings.
foreach($order['cart']['items'] as $item)
{
$itemId = $item['itemId'];
$item = $item['itemName']; /// <--- ! $item is no longer an item
$itemPrice = $item["itemPrice"];
$itemQty = $item["qty"];
}

How to show multiple array values in one row of php table

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 />';
}

parse.com - How to query and get json like array from parse.com using PHP SDK?

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");
}

PHP get array items based on string mask

i have an array with a bunch of records like in:
{
"ID": "38424",
"heading": "Nylies soek nuwe hoof",
"typeID": "1",
"datein": "2016-09-26 12:14:16",
"edited_datein": null,
"publishDate": "2016-09-23 00:00:00",
"category": {
"ID": "1",
"heading": "News",
"typeID": "3",
"datein": "2016-09-26 11:50:06",
"edited_datein": null,
"url": "news"
},
"authorID": "592",
"tags": "skool,school,hoof,headmaster,etienne burger"
}
i have another array with "columns" i want the records to be "filtered" by
{
"ID",
"heading",
"datein",
"category|heading",
"category|url"
}
i would like the result to create a multidimensional array based on the column items:
{
"ID": "38424",
"heading": "Nylies soek nuwe hoof",
"datein": "2016-09-26 12:14:16",
"category": {
"heading": "News",
"url": "news"
}
}
how do i achieve this? i'm totally stuck on this now :( busy trying a hack of array_combine now but i dont hold much hope it would work out
so after being stuck on this for many hours.. and posting it here. i found a solution
$new_list = array();
foreach ($n as $record) {
$new_list[] = filter_columns($columns, $record);
}
and the function:
function filter_columns($columns, $record, $pre="") {
$return = array();
foreach ($record as $key => $value) { // loop through the fields in the record
$str = $pre.$key; // create a string of the current key
if (in_array($str,$columns)){
$return[$key] = $value;
}
if (is_array($value)){
$return[$key] = filter_columns($columns, $value,$key."|"); // if the value is an array recall the function but prepend the current key| to the key mask
}
}
return $return;
}

Categories