Json array, get first value from each array key - php

What i'm trying to do is get the each array key and then associate the first "price" and "quantity" with each array key.
My array:
{
"32557580": {
"bids": [
{
"price": 2500,
"quantity": 38265661
},
{
"price": 2439,
"quantity": 57414444
},
{
"price": 2381,
"quantity": 1092179
},
{
"price": 2174,
"quantity": 27140648
}
],
"offers": [
{
"price": 2564,
"quantity": 33634591
},
{
"price": 2597,
"quantity": 27842125
},
{
"price": 2632,
"quantity": 925092
},
{
"price": 2667,
"quantity": 3565173
},
{
"price": 2778,
"quantity": 27589980
}
]
},
"32557581": {
"bids": [
{
"price": 4854,
"quantity": 33786947
},
{
"price": 4808,
"quantity": 22881344
},
{
"price": 4762,
"quantity": 2513747
},
{
"price": 4717,
"quantity": 2650000
},
{
"price": 4587,
"quantity": 15714786
}
],
"offers": [
{
"price": 4950,
"quantity": 31749492
},
{
"price": 5000,
"quantity": 3193999
},
{
"price": 5051,
"quantity": 2292463
},
{
"price": 5102,
"quantity": 34770816
},
{
"price": 5128,
"quantity": 2605693
}
]
},
"32557582": {
"bids": [
{
"price": 2532,
"quantity": 60354703
},
{
"price": 2500,
"quantity": 113667648
},
{
"price": 2439,
"quantity": 5125100
},
{
"price": 2222,
"quantity": 120803051
}
],
"offers": [
{
"price": 2564,
"quantity": 1492990
},
{
"price": 2597,
"quantity": 22121811
},
{
"price": 2632,
"quantity": 42119270
},
{
"price": 2667,
"quantity": 43680406
},
{
"price": 2703,
"quantity": 1176966
}
]
}
}
Example:
Id: 32557580
Price: 2500
Quantity: 38265661
Id: 32557581
Price: 4854
Quantity: 33786947
etc..
This is what i got so far
$obj = json_decode($result,true);
$all_keys = array_keys($obj);
foreach ($all_keys as $key => $value) {
echo 'Id: '.$value.'<br>';
}
Output from this is:
Id: 32557580
Id: 32557581
Id: 32557582
I'm not really sure where to go from here, i have tried look at multiple questions and answers elswere.
I tried adding another foreach inside the one i got but i only got the price and quantity from the first array key.
All help with getting me on the right track is appreciated.

Just loop the main array and get the first from bids and use that:
foreach($obj as $key => $value) {
$first = reset($value['bids']);
echo "ID: $key<br />";
echo "Price: " . $first['price'] . "<br />";
echo "Quantity: " . $first['quantity'] . "<br />";
}
Or use the index, which in this case is 0 but may not always be depending on the JSON:
foreach($obj as $key => $value) {
echo "ID: $key<br />";
echo "Price: " . $value['bids'][0]['price'] . "<br />";
echo "Quantity: " . $value['bids'][0]['quantity'] . "<br />";
}

Related

how to print a specific json key in php?

Here is my PHP code:
<?php
session_start();
include"smsciniz/vendor/autoload.php";
include"smsciniz/baglan.php";
//$insert = $DB->query("INSERT INTO sc_ulke(ulke_isim) VALUES(?)", array($_POST["ulke_isim"]));
$ulke = $DB->query("SELECT * FROM sc_ulke");
foreach ($ulke as $value) {
$url = file_get_contents("https://5sim.net/v1/guest/products/".trim($value["ulke_isim"])."/any");
$json = json_decode($url,true);
echo $json;
}
?>
And here is my JSON data:
"1688": {
"Category": "activation",
"Qty": 2000,
"Price": 14.83
},
"1xbet": {
"Category": "activation",
"Qty": 11413,
"Price": 19
},
"32red": {
"Category": "activation",
"Qty": 4113,
"Price": 7
},
"888casino": {
"Category": "activation",
"Qty": 4109,
"Price": 5
},
"99app": {
"Category": "activation",
"Qty": 5437,
"Price": 5
},
I want to print the area I marked but I don't know how to do.
I would be very happy if you could help me with an example, thank you in advance
"32red": {
"Category": "activation",
"Qty": 4113,
"Price": 7
},
We can iterate and find by particular key and print result using json_encode with JSON_PRETTY_PRINT
function findObjByKey($res, $keyToFind){
foreach ($res as $key => $value) {
if($key == $keyToFind) {
return $value;
}
}
return NULL;
}
$json = json_decode('
{"1688": {
"Category": "activation",
"Qty": 2000,
"Price": 14.83
},
"1xbet": {
"Category": "activation",
"Qty": 11413,
"Price": 19
},
"32red": {
"Category": "activation",
"Qty": 4113,
"Price": 7
},
"888casino": {
"Category": "activation",
"Qty": 4109,
"Price": 5
},
"99app": {
"Category": "activation",
"Qty": 5437,
"Price": 5
}}'
);
$res = findObjByKey($json, '32red');
$prittyPrint= json_encode($res, JSON_PRETTY_PRINT);
echo "<pre>".$prittyPrint."<pre>";
use json_encode($json['32red']) like this you can access any key in json

Changing a string in a json object

I'm trying to update a json file and I'm using laravel command to do it. In that file there are specific product codes that need to be changed. The code I'm doing to do this isn't working, it runs but nothing changes.
Here is my code
$old_code = 'P001';
$new_code = 'P011';
$productJson = json_decode(file_get_contents(storage_path('/Product 1/product.json')));
foreach($productJson as $key => $value){
str_replace($old_code, $new_code, $k);
}
file_put_contents(storage_path('/Product 1/product.json), json_encode($productJson, JSON_PRETTY_PRINT));
and this is my json file
{
"P001": {
"name": "Product 1",
"price": "200",
"category": "Shirts"
},
"P002": {
"name": "Product Test",
"price": "100",
"category": "Tops"
},
}
Its probably simpler to read the file and create a new JSON with the new codes like this
$s = '{"P001": {
"name": "Product 1",
"price": "200",
"category": "Shirts"
},
"P002": {
"name": "Product Test",
"price": "100",
"category": "Tops"
},
"P003": {
"name": "Product Test",
"price": "50",
"category": "Bottoms"
}
}';
$old_codes = ['P001', 'P002' ];
$new_codes = ['P011', 'P022' ];
$productJson = json_decode($s);
$new = new stdClass;
foreach($productJson as $key => $json){
$kk = array_search($key, $old_codes);
if ( FALSE !== $kk ) { // found
$new->{$new_codes[$kk]} = $json;
} else {
$new->{$key} = $json;
}
}
echo json_encode($new, JSON_PRETTY_PRINT);
//file_put_contents(storage_path('/Product 1/product.json'), json_encode($new, JSON_PRETTY_PRINT));
RESULT
{
"P011": {
"name": "Product 1",
"price": "200",
"category": "Shirts"
},
"P022": {
"name": "Product Test",
"price": "100",
"category": "Tops"
},
"P003": {
"name": "Product Test",
"price": "50",
"category": "Bottoms"
}
}

php how to extract values from an array

I have an array which I was able to get some details from my results like this:
$result["transaction"];
when doing this the follow is displayed:
{ "id": "wt13LbKmJ2",
"location_id": "EYGMFA",
"created_at": "2017-07-01T07:32:57Z",
"tenders":
[ { "id": "C6xMF",
"location_id": "MFA",
"transaction_id": "NvDAOOA9",
"created_at": "2017-07-01T07:32:57Z",
"note": "Offering",
"amount_money": { "amount": 100, "currency": "USD" }, "processing_fee_money": { "amount": 33, "currency": "USD" },
"customer_id": "14QEJXXM5TX",
"type": "CARD",
"card_details": { "status": "CAPTURED",
"card": { "brand": "VI", "last_4": "0000" },
"entry_method": "ON_FILE"
} } ],
"product": "EXTERNAL_API" }
How can I get my array to only display "100" where it say "amount":100
If I use:
$result["transaction"]["id"];
it will display only the id but I can't get the amount to display.
Use the following to check ur data and use last line like echo $data->tenders[0]->amount_money->amount;
<?php
$string='{ "id": "wt13LbKmJ2", "location_id": "EYGMFA", "created_at": "2017-07-01T07:32:57Z", "tenders": [ { "id": "C6xMF", "location_id": "MFA", "transaction_id": "NvDAOOA9", "created_at": "2017-07-01T07:32:57Z", "note": "Offering", "amount_money": { "amount": 100, "currency": "USD" }, "processing_fee_money": { "amount": 33, "currency": "USD" }, "customer_id": "14QEJXXM5TX", "type": "CARD", "card_details": { "status": "CAPTURED", "card": { "brand": "VI", "last_4": "0000" }, "entry_method": "ON_FILE" } } ], "product": "EXTERNAL_API" }';
$data=json_decode($string);
echo '<pre>';
print_r(json_decode($string));
echo '</pre>';
echo $data->id.'<br>';
echo $data->tenders[0]->id;
echo $data->tenders[0]->amount_money->amount;
?>
strong text
$result['transaction']['tenders'][0]['amount_money']['amount']
First you need to change $result object to array then fetch the data
do like this
$result=json_decode(json_encode($result,true),true);
Then
$result['transaction']['tenders'][0]['amount_money']['amount']
I thing it will help you.

Display value of json to output

Below is json code where i have o display its values. How to fetch the output as given below
$jsondata = '{
"flowers": [
{
"id": "1",
"name": "Le Grand Bouquet Blanc",
"price": "65",
"currency": "euro"
},
{
"id": "2",
"name": "Roses",
"price": "33",
"currency": "euro"
},
{
"id": "3",
"name": "Mandarine",
"price": "125",
"currency": "euro"
}
]
}';
Output should come like this
Name : Le Grand Bouquet Blanc, Price : 65
Name : Roses, Price : 33
Name : Mandarine, Price : 125
Total: 223 Euro
Any Help?
JSON decode, loop through the data and output the required text like so:
$data = json_decode($jsondata);
$total = 0;
foreach($data->flowers as &$datum) {
printf('Name : %s, Price: %d'.PHP_EOL, $datum->name, $datum->price);
$total += $datum->price;
}
printf('Total: %d Euro'.PHP_EOL, $total);
Read up on some basic PHP functions/concepts:
http://php.net/manual/en/function.json-decode.php
http://php.net/manual/en/control-structures.foreach.php
http://php.net/manual/en/function.printf.php
http://php.net/manual/en/function.echo.php
http://php.net/manual/en/language.operators.arithmetic.php
Try using json_decode() with true as second attribute to convert JSON it into array first.Then use foreach loop and get desired result.
<?php
$jsondata = '{
"flowers": [
{
"id": "1",
"name": "Le Grand Bouquet Blanc",
"price": "65",
"currency": "euro"
},
{
"id": "2",
"name": "Roses",
"price": "33",
"currency": "euro"
},
{
"id": "3",
"name": "Mandarine",
"price": "125",
"currency": "euro"
}
]
}';
$array = json_decode($jsondata,true);
//print_r($array);
$sum = 0;
foreach($array['flowers'] as $flowers)
{
echo "Name : ".$flowers['name'].",Price : ".$flowers['price'].PHP_EOL;
$sum+=$flowers['price'];
$currency = $flowers['currency'];
}
echo "Total:".$sum." ".$currency;
Try this.
$jsondata = '{
"flowers": [
{
"id": "1",
"name": "Le Grand Bouquet Blanc",
"price": "65",
"currency": "euro"
},
{
"id": "2",
"name": "Roses",
"price": "33",
"currency": "euro"
},
{
"id": "3",
"name": "Mandarine",
"price": "125",
"currency": "euro"
}
]
}';
$data = json_decode($jsondata,true);
echo "Name : " . $data['flowers'][0]['name'] . ' , Price: ' . $data['flowers'][0]['price'] ;

Loop through JSON array inside an array

Previously I was using a foreach loop to access the data in my JSON object but now I have nested an array inside an array. Here is my JSON
{
"name": "Takeaway Kings",
"menu": [
{
"starter": [
{
"name": "Samosas",
"price": 3.5
},
{
"name": "Chaat",
"price": 1.99
}
]
},
{
"dessert": [
{
"name": "Kulfi",
"price": 2.5
},
{
"name": "Kheer",
"price": 2.99
}
]
},
{
"main": [
{
"name": "Lamb Biryani",
"price": 4.5
},
{
"name": "Chicken Tikka Masala",
"price": 5.99
}
]
}
]
}
I am trying to loop through each array inside menu and then loop through what is in each nested array.
I was previously using this to output data before I changed the JSONObject layout.
<?php foreach($restaurant->menu->starter as $starter){
echo '<h3>'.$starter->name.'</h3><br><p>'.$starter->price.'</p><br>';
} ?>
try below code:
$json = '{
"name": "Takeaway Kings",
"menu": [
{
"starter": [
{
"name": "Samosas",
"price": 3.5
},
{
"name": "Chaat",
"price": 1.99
}
]
},
{
"dessert": [
{
"name": "Kulfi",
"price": 2.5
},
{
"name": "Kheer",
"price": 2.99
}
]
},
{
"main": [
{
"name": "Lamb Biryani",
"price": 4.5
},
{
"name": "Chicken Tikka Masala",
"price": 5.99
}
]
}
]
}';
echo '<pre>';
$json_arr = json_decode($json, true);
//print_r(call_user_func_array('array_merge',$json_arr['menu']));
echo "name: " . $json_arr['name'];
echo '<br />';
$menu_array = call_user_func_array('array_merge',$json_arr['menu']);
foreach ($menu_array as $name => $arr) {
echo '<br />';
echo "Menu name: " . $name;
foreach($arr as $v){
echo '<br />';
echo $v['name'].' : '.$v['price'];
}
}
output:
name: Takeaway Kings
Menu name: starter
Samosas: 3.5
Chaat: 1.99
Menu name: dessert
Kulfi: 2.5
Kheer: 2.99
Menu name: main
Lamb Biryani: 4.5
Chicken Tikka Masala: 5.99
Please Use Below Code For use Inner Values
$data=json_decode($data);
foreach($data->menu as $menu){
foreach($menu as $key => $value){
foreach($value as $key_inner => $value_inner){
echo '<h3>'.$value_inner->name.'</h3><br><p>'.$value_inner->price.'</p><br>';
}
}
}

Categories