I'm generating the following array in json format
[
{
"country": "China",
"amount": "1"
},
{
"country": "India",
"amount": "5"
},
{
"country": "India",
"amount": "317"
},
{
"country": "India",
"amount": "8"
},
{
"country": "India",
"amount": "2"
},
{
"country": "United States",
"amount": "213"
},
{
"country": "Iceland",
"amount": "263"
}
]
I've tried merging them with the following code
$newData = array();
$result = array_reduce(
$data,
function($newData, $value) {
$key = $value['country'];
if (!isset($newData[$key])) {
$newData[$key] = $value;
} else {
$newData[$key]['amount'] += $value['amount'];
}
return $newData;
},
$newData
);
my desired output is
[
{
"country": "China",
"amount": "1"
},
{
"country": "India",
"amount": "332"
},
{
"country": "United States",
"amount": "213"
},
{
"country": "Iceland",
"amount": "263"
}
]
As you can see the array is merged with all the country values grouped and the amount values added accordingly.
Use a simple foreach loop rather than array_reduce.
$newData = array();
foreach ($data as $e) {
if (isset($newData[$e['country']])) {
$newData[$e['country']]['amount'] += $e['amount'];
} else {
$newData[$e['country']] = $e;
}
}
$newData = array_values($newData);
Try this:
$newData = array();
foreach($oldData as $oldEntry){
foreach($newData as $newEntry){
if($oldEntry['country'] == $newEntry['country'])
$newEntry['country'] += $oldEntry['country'];
break;
}
$newData[] = array('country' => $oldEntry['country'], 'amount' => $oldEntry['amount'];
}
Related
I have a json reply from an api and i want some data.
the response looks like this:
{
"user_id": null,
"flight_info": {
"YU24268": {
"seat": {
"width": 45.72,
"pitch": 73.66
},
"delay": {
"ontime_percent": 0.66666669,
"max": 53,
"mean": 37,
"min": 28
}
},
"delay": {
"ontime_percent": 0.67741936,
"max": 305,
"mean": 33,
"min": 0
}
}
},
"travelpayouts_api_request": true,
"clean_marker": "75089",
"currency": "usd",
"internal": false,
"airports": {
"ORY": {
"rates": "12",
"city_code": "PAR",
"country_code": "FR",
"country": "France",
"time_zone": "Europe/Paris",
"name": "Paris Orly Airport",
"city": "Paris"
},
"SXF": {
"rates": "27",
"city_code": "BER",
"country_code": "DE",
"country": "Germany",
"time_zone": "Europe/Berlin",
"name": "Schonefeld Airport",
"city": "Berlin"
}
}
I use this code to find the airport i need (from the IATA code), but i can not get the city.
function find_city_from_IATA($my_value, $key1)
{
foreach ($key1->airports as $key=>$value) {
echo $key;
echo $my_value;
if ($key==$my_value) {
$city = json_decode($key1->airports,true);
// echo $key1->airlines['U2']->city;
$city = $city->city;
echo $city;
return $city;
}
}
}
How can i get the city name based on the airport IATA? (iata is the three letter code key that airports objects have).
Something like this:
$airport_code = 'ORY';
// $my_irpost_string is your json string
$data = json_decode($my_json_string, true);
$city = $data['airports'][$airport_code]['city'];
print($city);
You don't need foreach, as you already know the code. This means that your foreach + comparison is just array value # code.
This is a well known antipattern: https://softwareengineering.stackexchange.com/questions/348682/what-is-the-for-case-antipattern
Good morning guys!
I'm having a hard time trying to figure out how to arrange the following JSON:
{
"showElement": "1",
"degrees": [{
"Name": "Bachelor in Psychology",
"Number": "53",
"degree": "Bachelor's Degree"
}, {
"Name": "Certificate",
"Number": "56",
"degree": "Certificate"
}, {
"Name": "High School Diploma",
"Number": "28",
"degree": "High School"
}, {
"Name": "Bachelor in Sociology",
"Number": "109",
"degree": "Bachelor's Degree"
}]
}
Into this:
{
"showElement": "1",
"degrees": [{
"Name": "Bachelor in Psychology", "Bachelor in Sociology",
"Number": "53","109",
"degree": "Bachelor's Degree"
}, {
"Name": "Certificate",
"Number": "56",
"degree": "Certificate"
}, {
"Name": "High School Diploma",
"Number": "28",
"degree": "High School"
}]
}
Basically, put the same degrees in one place and have all the names of said degree separated by a comma
I already have this JSON decoded into a variable:
$data = json_decode($topDegrees[1]["diplomas"],true);
Thanks in advance for your help!
I came up with this
$json = <<<JSON
{
"showElement": "1",
"degrees": [{
"Name": "Bachelor in Psychology",
"Number": "53",
"degree": "Bachelor's Degree"
}, {
"Name": "Certificate",
"Number": "56",
"degree": "Certificate"
}, {
"Name": "High School Diploma",
"Number": "28",
"degree": "High School"
}, {
"Name": "Bachelor in Sociology",
"Number": "109",
"degree": "Bachelor's Degree"
}]
}
JSON;
$data = json_decode( $json, true );
$degrees = $data['degrees'];
$names = array_column($degrees, 'degree');
$count = array_count_values($names);
$duplicates = array_filter($count, function($var) {
return $var > 1;
});
foreach ( array_flip($duplicates) as $degree ) {
$filter = array_filter($degrees, function($var) use ($degree) {
return ( $var['degree'] === $degree );
});
$names = [];
$numers = [];
foreach ( $filter as $item ) {
$names[] = $item['Name'];
$numbers[] = $item['Number'];
}
$indices = array_keys($filter);
$index = array_shift($indices);
$degrees[$index]['Name'] = $names; // = join(', ', $names);
$degrees[$index]['Number'] = $numbers; // = join(', ', $numbers);
while ( count($indices) ) {
unset($degrees[array_shift($indices)]);
}
}
$data['degrees'] = $degrees;
print_r(json_encode($data));
// {"showElement":"1","degrees":[{"Name":["Bachelor in Psychology","Bachelor in Sociology"],"Number":["53","109"],"degree":"Bachelor's Degree"},{"Name":"Certificate","Number":"56","degree":"Certificate"},{"Name":"High School Diploma","Number":"28","degree":"High School"}]}
Your wanted json output is not valid, i have made an array structure in its place. If you want comma separated text, just use the join statements I've commented out.
$str = '{
"showElement": "1",
"degrees": [{
"Name": "Bachelor in Psychology",
"Number": "53",
"degree": "Bachelor\'s Degree"
}, {
"Name": "Certificate",
"Number": "56",
"degree": "Certificate"
}, {
"Name": "High School Diploma",
"Number": "28",
"degree": "High School"
}, {
"Name": "Bachelor in Sociology",
"Number": "109",
"degree": "Bachelor\'s Degree"
}]
}';
$str_arr = json_decode($str);
foreach($str_arr->degrees as $k=>$val){
if($val->degree == 'Bachelor\'s Degree'){
$new['Bachelor'][] = $val;
}else{
$new[] = $val;
}
}
foreach($new['Bachelor'] as $aa){
$nameStr[]= $aa->Name;
$numStr[] = $aa->Number;
}
$nameStr = implode(', ', $nameStr);
$numStr = implode(', ', $numStr);
$degree = 'Bachelor\'s Degree';
$new[] = (object) array($nameStr, $numStr, $degree);
unset($new['Bachelor']);
echo $json = json_encode($new);
echo "<pre>"; print_r(json_decode($json));
Hope this helps.
Demo here
This should do it:
<?php
$json = '{
"showElement": "1",
"degrees": [{
"Name": "Bachelor in Psychology",
"Number": "53",
"degree": "Bachelors Degree"
}, {
"Name": "Certificate",
"Number": "56",
"degree": "Certificate"
}, {
"Name": "High School Diploma",
"Number": "28",
"degree": "High School"
}, {
"Name": "Bachelor in Sociology",
"Number": "109",
"degree": "Bachelors Degree"
}]
}';
$items = json_decode($json, true);
$orderedItems = [];
$final = ['showElement' => 1];
foreach ($items['degrees'] as $item) {
$orderedItems[$item['degree']]['Name'][] = $item['Name'];
$orderedItems[$item['degree']]['Number'][] = $item['Number'];
$orderedItems[$item['degree']]['degree'] = $item['degree'];
}
foreach ($orderedItems as $order) {
$order['Name'] = (count($order['Name']) > 1) ? $order['Name'] : $order['Name'][0];
$order['Number'] = (count($order['Number']) > 1) ? $order['Number'] : $order['Number'][0];
$final['degrees'][] = [
'Name' => $order['Name'],
'Number' => $order['Number'],
'degree' => $order['degree']
];
}
echo json_encode($final);
I have a number of JSON such as:
ITEM 1:
{
"countries_views": [
{
"thecount": "563",
"country": "Greece"
},
{
"thecount": "48",
"country": "United States"
},
{
"thecount": "11",
"country": "Luxembourg"
},
{
"thecount": "7",
"country": "Germany"
},
{
"thecount": "6",
"country": "Cyprus"
},
{
"thecount": "2",
"country": "India"
},
{
"thecount": "2",
"country": "France"
},
{
"thecount": "2",
"country": "United Kingdom"
},
{
"thecount": "1",
"country": "Nigeria"
},
{
"thecount": "1",
"country": "Russia"
}
]
}
ITEM 2:
{
"countries_views": [
{
"thecount": "1037",
"country": "Greece"
},
{
"thecount": "17",
"country": "United States"
},
{
"thecount": "17",
"country": "Cyprus"
},
{
"thecount": "12",
"country": "Germany"
},
{
"thecount": "11",
"country": ""
},
{
"thecount": "4",
"country": "United Kingdom"
},
{
"thecount": "4",
"country": "Australia"
},
{
"thecount": "2",
"country": "Belgium"
},
{
"thecount": "1",
"country": "Russia"
},
{
"thecount": "1",
"country": "Argentina"
}
]
}
And so on! What i need to do is Combine/Merge this Data in 1 array with PHP and i need to add the values of Duplicates. The end result should look something like this:
{
"countries_views": [
{
"thecount": "**1600**",
"country": "Greece"
},
{
"thecount": "**65**",
"country": "United States"
},
etcetcetc
]
}
First parse the JSON data, and we just traverse the array to find the duplicates and add them up.
<?php
// emit the code of parsing json. (see function json_decode)
$arr1 = [
(object)['thecount' => 563, 'country' => 'Greece'],
(object)['thecount' => 12, 'country' => 'US'],
(object)['thecount' => 15, 'country' => 'UK'],
];
$arr2 = [
(object)['thecount' => 1563, 'country' => 'Greece'],
(object)['thecount' => 152, 'country' => 'CN'],
];
foreach ($arr1 as $each) {
$exists = false;
foreach ($arr2 as &$e) {
if ($e->country == $each->country) {
$e->thecount += $each->thecount;
$exists = true;
}
}
if (!$exists) {
array_push($arr2, $each);
}
}
$res = $arr2;
var_dump($res);
Here is how to get $arr1, $arr2, in your example.
<?php
$arr1_obj = json_decode($item1);
$arr2_obj = json_decode($item2);
$arr1 = $arr1_obj->countries_views;
$arr2 = $arr2_obj->countries_views;
I have a JSON array like this
$countries = [
{
"id": "1",
"country_name": "Afghanistan",
},
{
"id": "2",
"country_name": "Albania",
},
{
"id": "3",
"country_name": "Algeria",
},
{
"id": "4",
"country_name": "American Samoa",
}
..
..
..
{
"id": "50",
"country_name": "Zimbabwe",
}
];
The following array contains, the list of countries that I need to sort to top
$top_countries = ['United States', 'United Kingdom', 'German'];
What is the best way to sort the above array as follows
$countries = [
{
"id": "30",
"country_name": "United States",
},
{
"id": "31",
"country_name": "United Kingdom",
},
{
"id": "20",
"country_name": "German",
},
{
"id": "1",
"country_name": "Afghanistan",
},
{
"id": "2",
"country_name": "Albania",
},
{
"id": "3",
"country_name": "Algeria",
},
{
"id": "4",
"country_name": "American Samoa",
}
..
..
..
{
"id": "50",
"country_name": "Zimbabwe",
}
];
// index "value" of country by name
$top = array_flip($top_countries);
usort($countries, function($a, $b) use ($top) {
// get "value" for each country, if it is in index
$aValue = isset($top[$a->country_name])?$top[$a->country_name]:-1;
$bValue = isset($top[$b->country_name])?$top[$b->country_name]:-1;
if ($aValue == $bValue) {
// preserve "original order", assuming they were ordered by id
return $a->id < $b->id ? -1 : 1;
}
return $aValue < $bValue ? 1:-1;
});
I am newbie to php ,trying to create a nested json array in php but not getting the desired json format.
desired format
{
"offers": [
{
"offerId": "1",
"offerName": "shirts",
"price": "1980",
"storeName": "peter england"
},
{
"offerId": "2",
"offerName": "shirts",
"storeId": "3",
"price": "2970",
"storeName": "peter england"
}
],
"brands": [
{
"brandName": "peter england",
"brandId": "5"
},
{
"brandName": "ruggers",
"brandId": "4"
}
],
"stores": [
{
"storeName": "peter england",
"storeId": "3"
},
{
"storeName": "peter england",
"storeId": "4"
}
],
"filters": [
{
"0": {
"filter": "M",
"filterId": "11"
},
"1": {
"filter": "S",
"filterId": "12"
},
"filterName": "size"
},
{
"0": {
"filter": "red",
"filterId": "13"
},
"1": {
"filter": "blue",
"filterId": "14"
},
"filterName": "colour"
}
]
}
but getting this format
{
"offers": [
{
"offerId": "1",
"offerName": "shirts",
"image": "http://www.offersmashup.com/testing/store/upload/sml_p1.jpg",
"brandId": "5",
"storeId": "3",
"price": "1980",
"offer": "Off-20",
"storeName": "peter england"
},
{
"offerId": "2",
"offerName": "shirts",
"image": "http://www.offersmashup.com/testing/store/upload/sml_p2.jpg",
"brandId": "5",
"storeId": "3",
"price": "2970",
"offer": "Off-30",
"storeName": "peter england"
}
],
"brands": [
{
"brandName": "peter england",
"brandId": "5"
},
{
"brandName": "ruggers",
"brandId": "4"
}
],
"stores": [
{
"storeName": "peter england",
"storeId": "3"
},
{
"storeName": "peter england",
"storeId": "4"
}
],
"filters": {
"0": {
"filter": "M",
"filterId": "11"
},
"1": {
"filter": "S",
"filterId": "12"
},
"filterName": "size"
}
}
my php code is below
$dbFactory = new DBFactory();
$jsonArray = array();
if ($subcatid != '')
{
$p2 = $dbFactory->sel_product3($subcatid, $area_value);
if (count($p2) > 0)
{
for ($j = 0; $j < count($p2); $j++)
{
$p3 = $dbFactory->sel_store($p2[$j]['STORE_ID']);
$temp['offers'][] = array(
"offerId" => $p2[$j]['P_ID'],
"offerName" => $p2[$j]['P_NAME'],
"image" => $url . $p2[$j]['P_ID'] . '.jpg',
"brandId" => $p2[$j]['BRAND_ID'],
"storeId" => $p2[$j]['STORE_ID'],
"price" => $p2[$j]['PRICE'],
"offer" => $p2[$j]['OFFER'],
"storeName" => $p3[0]['S_NAME']
);
$jsonArray = $temp;
}
}
}
// filters code=================
/*code to retrive brnads and stores goes here*/
foreach($res as $value)
{
$br = $dbFactory->sel_brand($value);
$temp["brands"][] = array("brandName" => $br[0]['BRAND_NAME'] ,"brandId"=>$br[0]['BID'] );
$jsonArray = $temp;
}
foreach($store_value as $value)
{
$sr = $dbFactory->sel_store($value);
$temp["stores"][] = array("storeName" => $sr[0][S_NAME] ,"storeId"=>$sr[0][S_ID] );
$jsonArray = $temp;
}
$parentCatId = $dbFactory->getparentcatId($subcatid);
$fg = $dbFactory->get_filtergroup($parentCatId[0]['PARENT_ID']);
for ($i = 0; $i < count($fg); $i++)
{
$f = $dbFactory->sel_filter($fg[$i][F_ID]);
$temp['filters'] = array();
$temp['filters']['filterName'] = $fg[$i][FNAME];
for ($j = 0; $j < count($f); $j++)
{
$temp['filters'][] = array("filter"=>$f[$j][FNAME],"filterId"=>$f[$j][F_ID] );
}
array_push($jsonArray, $temp);
}
$jsonArray = $temp;
echo json_encode($jsonArray);
tried a lot to get the desired json format but failed.please help me out to solve this problem