Duplicate fields/values from JSON object array in php - php

I am working on a website in which I want to remove duplicate fields from JSON object array.
The JSON object array which I have is:
"rental_rates": [{
"rate_id": 170,
"uuid": "a3a14d20-63d1-11e8-b047-89e5d3a9513d",
"owner_id": 38,
"item_id": 394,
"name": "daily",
"term": "daily",
"currency": "dollars",
"rate": "56.00",
"min_charge": "56.00",
"created_at": "2018-05-30 06:20:43",
"updated_at": "2018-05-30 06:21:07"
}, {
"rate_id": 172,
"uuid": "a3a1c500-63d1-11e8-8740-8925bbb8ada8",
"owner_id": 38,
"item_id": 394,
"name": "weekly",
"term": "weekly",
"currency": "dollars",
"rate": "677.00",
"min_charge": "56.00",
"created_at": "2018-05-30 06:21:00",
"updated_at": "2018-05-30 06:21:07"
}],
The code which I am using in order to pull fields/values form JSON object array is:
foreach ($data['item']->rental_rates as $rental_rate)
{
echo '<span class="rental_term" style="text-align:right">'."minimum".'</span>';
echo '<span class="rental_price" style="text-align:right">$'.floatval($rental_rate->min_charge).'</span><br>';
}
The above code is pulling the following data and I want only one to be shown.
minimum $56
minimum $56
Problem Statement:
I am wondering what changes I need to make in the foreach loop so it pull only one field and value like this,
minimum $56

Two ways. Store what has already been displayed and check for it:
$shown = array();
foreach ($data['item']->rental_rates as $rental_rate)
{
if(!in_array($rental_rate->min_charge, $shown)) {
$shown[] = $rental_rate->min_charge;
echo '<span class="rental_term" style="text-align:right">'."minimum".'</span>';
echo '<span class="rental_price" style="text-align:right">$'.floatval($rental_rate->min_charge).'</span><br>';
}
}
Or create an array indexed by the min_value so there will only ever be one (only works on objects as of PHP >= 7.0.0):
$rates = array_column($data['item']->rental_rates, null, 'min_charge');
foreach $rates as $rental_rate)
{
echo '<span class="rental_term" style="text-align:right">'."minimum".'</span>';
echo '<span class="rental_price" style="text-align:right">$'.floatval($rental_rate->min_charge).'</span><br>';
}
For PHP < 7.0.0, decode the JSON as an array passing true as the second argument and use $data['item']['rental_rates'] and $rental_rate['min_charge'] in the code above instead.

Related

How do I add a document to existing filled collection?

I am building an eShop for educational purposes and I need to handle the orders from a user. A user has a basket which is getting filled with products. If he decides buy another product I have insert a document into the existing collection of the card
Current MongoDB collection:
{
"_id": {
"$oid": "61f3d79c921000006000547d"
},
"username": "mike",
"products": {[
"number": "3",
"name": "Honduras",
"price": 7,
"stock": 10,
]},
"status": "UNPAID"
}
By adding another product, needs to be inserted in the existing collection in the field of products.
Expected to look like:
{
"_id": {
"$oid": "61f3d79c921000006000547d"
},
"username": "mike",
"products": {[
"number": "3",
"name": "Honduras",
"price": 7,
"stock": 10,
], [
"number": "4",
"name": "India",
"price": 10,
"stock": 11,
]},
"status": "UNPAID"
}
I am using PHP for the back end operations. The script that I wrote it is simple. I am searching if orders with user's username exist. If they exist then I lock the current order and make the operations needed.
I think that I am missing something in syntax of the update for the purpose described above:
PHP script:
if (isset($_POST['add'])){
// Ordered by name from URL
$username = $_GET['username'];
// Product info
$name = $_POST['add'];
// Finds the product selected from products
$product = $collection -> findOne(array("name" => "$name"));
// Serialize product to be added.
$json = MongoDB\BSON\toJSON(MongoDB\BSON\fromPHP($product));
// Searching for order from certain user
$collection = $db -> orders;
$exists = $collection -> findOne(array("username" => "$username"));
if (!is_null($exists)){
// The problem is here (maybe?)
$exists->updateOne(
array("products" => {}),array('$set'=>$json);
);
}
Any help and suggestions would be really appreciated!
Well, you need to use something like below
db.collection.update(
{find Condition},
{$push: {products : {key: value, key2: value 2}}
)
Here the catch is push. It adds an element to array. Here the element is an object.

How to get values from nested json in php [duplicate]

This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 1 year ago.
I have this json file
{
"success": true,
"data": {
"total": "2",
"returned": 2,
"start": 0,
"limit": 10,
"transactions": [
{
"id": "16393567",
"type": "Credit",
"currency": "BTC",
"amount": "0.00019449",
"when": "2021-09-03 10:27:48",
"rental": "3411209",
"rig": "205363",
"status": "Pending",
"pending_seconds": "716202"
},
{
"id": "16377905",
"type": "Credit",
"currency": "BTC",
"amount": "0.00000203",
"when": "2021-09-01 11:42:47",
"rental": "3408621",
"rig": "205363",
"status": "Cleared",
"pending_seconds": 0
}
]
}
}
I am able to get values under data with this code
$jsonCont = file_get_contents('temp.json');
$content = json_decode($jsonCont, true);
$rig_detail= $content['data']['total'];
$rig_detail= $content['data']['returned'];
$rig_detail= $content['data']['start'];
$rig_detail= $content['data']['limit'];
My problem exists where I try and get data from "transactions" I have tried
$rig_detail= $content['data']['transactions']['id'];
This however does not give me what I expected. What do I need to do to access the data within the transactions section?
the are more elements in $content['data']['transactions'], so it is an array.
Try something like this:
$rig_detail= $content['data']['transactions'][0]['id'];

Extract Required info from json nested nested loops

I am using php to fetch live rates for cryptocurrency from coin market cap api. Here is the response that i get from the api. I want to extract the USD price from this nested response. I tried this :
$rate = json_decode($response,true);
echo $rate['data'][0]['quotes'][0]['USD'][0];
But it didn't worked. The json response that i got is :
{
"status": {
"timestamp": "2020-09-26T12:59:24.147Z",
"error_code": 0,
"error_message": null,
"elapsed": 13,
"credit_count": 1,
"notice": null
},
"data": {
"BTC": {
"id": 1,
"name": "Bitcoin",
"symbol": "BTC",
"slug": "bitcoin",
"num_market_pairs": 9251,
"date_added": "2013-04-28T00:00:00.000Z",
"tags": [
"mineable",
"pow",
"sha-256",
"store-of-value",
"state-channels"],
"max_supply": 21000000,
"circulating_supply": 18500450,
"total_supply": 18500450,
"is_active": 1,
"platform": null,
"cmc_rank": 1,
"is_fiat": 0,
"last_updated": "2020-09-26T12:58:38.000Z",
"quote": {
"USD": {
"price": 10707.7229962,
"volume_24h": 20866014910.9822,
"percent_change_1h": -0.156013,
"percent_change_24h": 0.675761,
"percent_change_7d": -2.97789,
"market_cap": 198097693905.04828,
"last_updated": "2020-09-26T12:58:38.000Z"
}
}
}
}
}
Thank you guys for your help!
Try this way if you need to grab the USD price only of BTC,
echo $rate['data']['BTC']['quote']['USD']['price'];
Otherwise need to loop through the API response and grab the value from it but the index path ['quote']['USD']['price'] should be more or less the same as I pointed.
DEMO: https://3v4l.org/gi7jB
You need to take care of indexes. When using associative arrays (hashmaps) you can not use numeric indexes.
foreach ($rate['data'] as $currency => $currencyData) {
echo "$currency: {$currencyData['quote']['USD']['price']}\n";
}
BTC: 10707.7229962

Search multidimensional array with Key name and return values as result

I am PHP beginner so please be patient with me. I spent couple of hours going through many threads already on multidimensional arrays search but none of them fits my situation. Sounds really simple but kind of stuck as I want to search by key name and retrieve values against it.
Tried some methods like array_column but returns an empty array.
I simply want to loop through array finding key name as: "largeImageURL" from all the array elements and want to return its values.
{
"total": 4692,
"totalHits": 500,
"hits": [
{
"id": 195893,
"pageURL": "https://pixabay.com/en/blossom-bloom-flower-195893/",
"type": "photo",
"tags": "blossom, bloom, flower",
"previewURL": "https://cdn.pixabay.com/photo/2013/10/15/09/12/flower-195893_150.jpg"
"previewWidth": 150,
"previewHeight": 84,
"webformatURL": "https://pixabay.com/get/35bbf209e13e39d2_640.jpg",
"webformatWidth": 640,
"webformatHeight": 360,
"largeImageURL": "https://pixabay.com/get/ed6a99fd0a76647_1280.jpg",
"fullHDURL": "https://pixabay.com/get/ed6a9369fd0a76647_1920.jpg",
"imageURL": "https://pixabay.com/get/ed6a9364a9fd0a76647.jpg",
"imageWidth": 4000,
"imageHeight": 2250,
"imageSize": 4731420,
"views": 7671,
"downloads": 6439,
"favorites": 1,
"likes": 5,
"comments": 2,
"user_id": 48777,
"user": "Josch13",
"userImageURL": "https://cdn.pixabay.com/user/2013/11/05/02-10-23-764_250x250.jpg",
},
{
"id": 73424,
...
},
...
]
}
First of all, you have to convert your JSON object to an array and compare like below.
$results = json_decode($your_array);
$match_result = [];
foreach($results['hits'] as $result) {
if (isset($result['largeImageURL']) {
$match_result [] = $result['largeImageURL'];
}
}
print_r($match_result);
You have to decode your JSON response into an array and loop through hits array till you find the key and return the data.
$returnArr = array();//to store values of largeImageURL
$json = "<json response>";//your json string here
$decoded_json = json_decode($json, true);//convert json to an array
//now we will loop through hits
foreach($decoded_json['hits'] as $hit){
$returnArr[] = $hit['largeImageURL'];
}
print_r($returnArr);

php json parsing objects

I have a JSON file that I need to parse. I'm new to php and trying to figure out how to correctly parse the object. My question is: How do I parse the objects of an object that have different names
One object has the name Thresh the next object in the list has the name Aatrox the name of the top level object is data
This is what the JSON looks like. I can access the information if I know the name of the object $champion = $jfo->data->Thresh; but I don't want to have to type in all the names of the champions. Is there an easy way to obtain all the separate objects without knowing the names? Maybe regex?
"data": {
"Thresh": {
"id": 412,
"key": "Thresh",
"name": "Thresh",
"title": "the Chain Warden",
"image": {
"full": "Thresh.png",
"sprite": "champion3.png",
"group": "champion",
"x": 336,
"y": 0,
"w": 48,
"h": 48
},
"Aatrox": {
"id": 266,
"key": "Aatrox",
"name": "Aatrox",
"title": "the Darkin Blade",
"image": {
"full": "Aatrox.png",
"sprite": "champion0.png",
"group": "champion",
"x": 0,
"y": 0,
"w": 48,
"h": 48
},
If you want to go through each champion, I'd recommend using a foreach loop in PHP. You can use it as such:
foreach($json->data as $champion)
{
// Do something
}

Categories