How to iterate arrays nested in arrays [duplicate] - php

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

Related

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

Search item on json object PHP [duplicate]

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.

Printing nested associative array in PHP

I'm using this code $json_output = (json_decode($json, true)); to transform from JSON to an associative array in PHP.
The resulting array looks too compĺex to me, I need to print only some keys and values but they are nested and so far I haven't been able to do it, the examples I had follow for printing are too basic for this.
This is part of my JSON:
{
"project": {
"company": "Company Name SA de CV",
"name": "Project Name",
"files": [
{
"project-id": "666666",
"filenameOnDisk": "HH-ORG-CMD-GUI-File.docx",
"uploaded-date": "2018-01-29T21:20:56Z",
"private": "0",
"version-id": "3939061",
"status": "active",
"tags": [
{
"name": "OPD",
"id": "25047",
"color": "#9e6957"
}
],
"id": "3796128",
"last-changed-on": "2018-01-29T21:21:46Z",
"versions": [],
"uploaded-by-user-first-name": "Someone",
"uploaded-by-user-last-name": "Anything",
"name": "HH-ORG-CMD-GUI-GUIA_RAPIDA_PARA_CREAR_PROCESOS",
"size": "262747",
"category-name": "Instructivos"
},
{
"project-id": "666",
etc...,
},
When parsed looks like
How do I print (lets say) filenameOnDisk and id keys of the Files array.
I don't know how to get to that nested array.
echo $json_output['project']['files'][0]['project-id'];
echo $json_output['project']['files'][0]['filenameOnDisk'];
echo $json_output['project']['files'][0]['version-id'];
Or you could put it in a foreach loop using an array of values you want (as long as they're all in the 'files' array). Eg.
$wantedValues = array("project-id","filenameOnDisk","version-id");
foreach ($wantedValues as $value) {
echo $json_output['project']['files'][0][$value];
}
I Just needed to add a couple of lines at the code provided by #SeeSamRun in order to get the full "Files" array.
$filesArray = $json_output['project']['files'];
$filesSize = count($filesArray);
$wantedValues = array("project-id","filenameOnDisk","version-id");
for ($i=0; $i < $filesSize; $i++) {
foreach ($wantedValues as $value) {
echo $json_output['project']['files'][$i][$value];
}
}

JSON KEY VALUE LOOP PHP [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
i have a JSON with this data:
$data = "meta_data":[
{
"id":2279,
"key":"codice_fiscale",
"value":"gege"
},
{
"id":2280,
"key":"numero_tessera_titolare",
"value":"gre"
},
{
"id":2281,
"key":"classe_tessera_titolare",
"value":"gre"
},
{
"id":2282,
"key":"tratta_da",
"value":"gre"
},
{
"id":2283,
"key":"tratta_a",
"value":"grge"
},
{
"id":2284,
"key":"studente",
"value":"studente"
}];
I need to loop all "key" and when i find the key that i need (in this case "studente") i need to get the value stored in "value".
How can i do this in PHP?
EDIT
I tried this:
foreach($data as $row){
if($row->key=='studente'){
$var = $row->value;
}
}
The best / most efficient way is to write a foreach loop with a break.
Code: (Demo)
$json = '{
"meta_data": [
{
"id": 2279,
"key": "codice_fiscale",
"value": "gege"
},
{
"id": 2283,
"key": "tratta_a",
"value": "grge"
},
{
"id": 2284,
"key": "studente",
"value": "studente"
}
]}';
$data = json_decode($json, true);
$search='studente';
$found=false;
foreach($data['meta_data'] as $d){
if($d['key']==$search){
$found=$d['value'];
break;
}
}
echo $found?$found:"$search not found";
Output:
studente
First, $data is not a valid json. You can use json_decode() to get a php array representation of your json string. Then loop through array.
Example:
$json = '{
"meta_data": [
{
"id": 2279,
"key": "codice_fiscale",
"value": "gege"
},
// other items...
{
"id": 2283,
"key": "tratta_a",
"value": "grge"
},
{
"id": 2284,
"key": "studente",
"value": "studente"
}
]}';
$data = json_decode($json, true);
//var_dump($data);
foreach($data['meta_data'] as $key => $item) {
if (isset($item['value']) && $item['value'] == 'studente') {
var_dump($item);
}
}

Json php formatted data

I have a json file like this
{
"id": "123456789012345",
"members": {
"data": [
{
"name": "Dylan John",
"administrator": false,
"id": "12341234"
},
{
"name": "Test user",
"administrator": false,
"id": "43214321"
},
{
"name": "Demo user",
"administrator": false,
"id": "55445544"
},
{
"name": "Fake user",
"administrator": false,
"id": "11991199"
}
],
"paging": {
"next": "www.123456demo12345.com"
}
}
}
I need to extract the id of each name.
I just start my php code like that but simply display only the master id:
<?php
$url = "http://www.1234demo1234fake.com/user.json";
$json = file_get_contents($url);
$data = json_decode($json, TRUE);
echo $data[id]; //echo master id
echo $data[members][data][id];
?>
You have to iterate over $data['members']['data'] and print $data['members']['data'][$i]['id'].
Your JSON object contains property members again members has property data.
Now data is an array.
Just loop over data, you get array of objects (members), fetch property id from it.
<?php
$abc = json_decode($your_json_sting);
$membersData = $abc->members->data;
$memberIds = array();
foreach ($membersData as $mem) {
$memberIds[] = $mem->id;
}
echo '<pre>';print_r($memberIds);echo '</pre>';
?>

Categories