I am trying to read json file using php code listed below but I am unable to assign these values to local variables.
Can someone help me explain what am I doing wrong?
<?php
$file = "http://localsurch.com/deals2.txt";
$response = json_decode(file_get_contents($file), true);
//print_r($response);
foreach ($response as $mydeal)
{
$category = $mydeal->category->name;
$title = $mydeal->websiteTitle;
$finePrint = $mydeal->finePrint;
$imageURL = $mydeal->imageURL;
$merchant = $mydeal->merchant->displayName;
$streetaddress1 = $mydeal->redemptionLocations->addressStreet1;
}
?>
Array
(
[date] => 28-Jun-14 5.46.34.871 PM
[deals] => Array
(
[0] => Array
(
[category] => Array
(
[name] => Repair & Services
[path] => Array
(
[0] => Automotive
[1] => Repair & Services
)
)
[websiteTitle] => Three Full-Service Oil Changes, Tire Rotations, and More
[description] => <p>Since 1988, Planet Super Saver has been saving members thousands of dollars on their automotive maintenance and repairs nationwide. Their goal is to unite you with trustworthy, top-notch service centers in your area at a huge savings. The service center's goal is to introduce themselves to you with the hopes you'll become a long-term customer through their honesty and professional service you can depend on.</p>
$30 ($179 value) for an auto maintenance package
Includes three complete oil changes, two tire rotations, diagnostics, and inspections
Preventative care can mean big savings down the road
Efficient, friendly professionals get the job done right
[finePrint] => <ul><li><b>Online redemption required at planetsupersaver.com; a punch card will be mailed within 5 business days</b></li>
Punch card is valid for 1 year from date of redemption
Appointments are required and subject to availability; for more information call Planet Super Saver customer support at 480-921-8282
Merchant cancellation/re-scheduling policy of 24 hours applies; voucher subject to forfeiture
Punch Card is transferable between vehicles owned by the same person or family and may be used over multiple visits
Valid only for location selected at time of purchase
Cannot be combined with any other offer or promotion
Buy as many as you like; send as many as you like as gifts
Complete oil change includes up to 5 quarts of oil, lube, and filter. Additional quarts and synthetic or diesel oil are available for an extra fee
Some services calling for refrigerant and coolant will require an extra fee
$4.50 disposal fee, tax, and gratuity are not included
Available for use immediately after purchase
PROMOTIONAL VALUE EXPIRES 180 DAYS FROM THE PURCHASE DATE
PAID VALUE EXPIRES 5 YEARS FROM THE PURCHASE DATE
[asin] => B00LBL758W
[imageURL] => /images/G/01/ember/deals/c617b334d1893eae7cbc94301fab538c5880b3e24f95669d10ad118fe38eaadc
[merchant] => Array
(
[displayName] => Planet Super Saver
)
[offerEndTime] => 1411714800000
[options] => Array
(
[0] => Array
(
[title] => 7111 Sudley Rd Location - Auto Maintenance Package (Three Complete Oil Changes, Two Tire Rotations, Diagnostics, and Inspections)
[value] => Array
(
[currencyCode] => USD
[amountInBaseUnit] => 17900
)
[price] => Array
(
[currencyCode] => USD
[amountInBaseUnit] => 3000
)
)
[1] => Array
(
[title] => 7892 Sudley Rd Location - Auto Maintenance Package (Three Complete Oil Changes, Two Tire Rotations, Diagnostics, and Inspections)
[value] => Array
(
[currencyCode] => USD
[amountInBaseUnit] => 17900
)
[price] => Array
(
[currencyCode] => USD
[amountInBaseUnit] => 3000
)
)
)
[geographies] => Array
(
[0] => Array
(
[seoName] => northern-virginia
[displayName] => Northern Virginia
)
[1] => Array
(
[seoName] => montgomery-county
[displayName] => Montgomery County
)
[2] => Array
(
[seoName] => washington-dc
[displayName] => Washington, D.C.
)
[3] => Array
(
[seoName] => arlington-alexandria
[displayName] => Arlington / Alexandria
)
)
[redemptionLocations] => Array
(
[0] => Array
(
[addressPostalCode] => 20109
[addressStateOrProvince] => VA
[addressStreet1] => Battlefield BP
[addressStreet2] => 7111 Sudley Rd
[geography] => Array
(
[displayName] => Northern Virginia
)
[latitude] => 38.799067
[longitude] => -77.518125
[phoneNumber] => 480-921-8282
)
)
)
[1] => Array
(
[category] => Array
(
[name] => Indian
[path] => Array
(
[0] => Restaurants
[1] => Indian
)
)
[websiteTitle] => $15 to Spend on Food and Drink
[description] => <p>Dine on savory Pakistani and Indian cuisine at this eatery, where everything is Halal. Enjoy kabobs, curries, and Biryani—but don't miss out on their house specialty, The Karahi, with chicken, beef, goat, lamb, fish or paneer:</p>
$7 for $15 to spend on food and nonalcoholic drinks
Varied menu features wraps, salads, curry, and grill favorites
We recommend the charcoal chicken combo, which includes warm naan and tasty sides
Charcoal Chicken's Website | Facebook
[finePrint] => <ul><li>Limit 2 per customer </li>
Limit 1 per table per visit
Valid only for dine-in or takeout
Excludes alcohol
Excludes holidays
Entire value must be used in a single visit
Available for use beginning the day after purchase
PROMOTIONAL VALUE EXPIRES FOLLOWING OCTOBER 12, 2014
PAID VALUE EXPIRES 5 YEARS FROM THE PURCHASE DATE
[asin] => B00L1OHHZK
[imageURL] => /images/G/01/ember/deals/ab799f011c6041f1d99b776d4e11f8b7e0e3c2422a6fd1ccae595d5c70c2937c
[merchant] => Array
(
[displayName] => Charcoal Chicken
)
[offerEndTime] => 1405148400000
[options] => Array
(
[0] => Array
(
[title] => $15 to Spend on Food and Nonalcoholic Drinks
[value] => Array
(
[currencyCode] => USD
[amountInBaseUnit] => 1500
)
[price] => Array
(
[currencyCode] => USD
[amountInBaseUnit] => 700
)
)
)
[geographies] => Array
(
[0] => Array
(
[seoName] => northern-virginia
[displayName] => Northern Virginia
)
)
[redemptionLocations] => Array
(
[0] => Array
(
[addressPostalCode] => 20151
[addressStateOrProvince] => VA
[addressStreet1] => 13969 Metrotech Drive
[addressStreet2] =>
[geography] => Array
(
[displayName] => Northern Virginia
)
[latitude] => 38.895558
[longitude] => -77.4283257
[phoneNumber] => 703-953-3700
)
)
)
[2] => Array
(
[category] => Array
(
[name] => Watches
[path] => Array
(
[0] => Retail Products
[1] => Watches
)
)
[websiteTitle] => Watch-Battery Replacement or Watch Repair
[description] => <p>Fashion Time is the premier spot in Maryland and Virginia to buy and repair all your timepieces. Whether you're in the market for a grandfather clock or a new stem for your watch, these time experts can help. </p><ul><li>$6 ($13 value) for a battery replacement for a non-Swiss watch</li><li>$19 ($40 value) for a battery replacement for a Swiss watch</li><li>$20 for $40 to spend on watches or watch repair</li><li>Old-fashioned craftsmen and technicians are experts in timepieces </li></ul><p>Fashion Time on Facebook</p>
[finePrint] => <p></p><ul><li>Buy as many as you like; send as many as you like as gifts<br></li><li>Limit 1 voucher per customer per visit<br></li><li>Valid only for option purchased<br></li><li>Excludes sale items<br></li><li>Valid only for in-store purchases<br></li><li>Cannot be combined with any other offers or promotions<br></li><li>Entire value per voucher must be used in a single visit </li><li>Available for use beginning the day after purchase</li><li>PROMOTIONAL VALUE EXPIRES 180 DAYS FROM THE PURCHASE DATE</li><li>PAID VALUE EXPIRES 5 YEARS FROM THE PURCHASE DATE</li></ul><p></p>
[asin] => B00KO8KOMM
[imageURL] => /images/G/01/ember/deals/7d648552caa12945ae14ee4554d255b21e1ae7739fce1f4be07ebf83e495e4
[merchant] => Array
(
[displayName] => Fashion Time
)
[offerEndTime] => 1411542000000
[options] => Array
(
[0] => Array
(
[title] => Battery Replacement for a Non-Swiss Watch
[value] => Array
(
[currencyCode] => USD
[amountInBaseUnit] => 1300
)
[price] => Array
(
[currencyCode] => USD
[amountInBaseUnit] => 600
)
)
[1] => Array
(
[title] => Battery Replacement for a Swiss Watch
[value] => Array
(
[currencyCode] => USD
[amountInBaseUnit] => 4000
)
[price] => Array
(
[currencyCode] => USD
[amountInBaseUnit] => 1900
)
)
)
[geographies] => Array
(
[0] => Array
(
[seoName] => northern-virginia
[displayName] => Northern Virginia
)
[1] => Array
(
[seoName] => montgomery-county
[displayName] => Montgomery County
)
)
[redemptionLocations] => Array
(
[0] => Array
(
[addressPostalCode] => 20166
[addressStateOrProvince] => VA
[addressStreet1] => 2110 D Dulles Town Ctr
[addressStreet2] =>
[geography] => Array
(
[displayName] => Northern Virginia
)
[latitude] => 39.035249
[longitude] => -77.42987
[phoneNumber] => 571-434-8875
)
[1] => Array
(
[addressPostalCode] => 22102
[addressStateOrProvince] => VA
[addressStreet1] => 1961 Chain Bridge Rd
[addressStreet2] =>
[geography] => Array
(
[displayName] => Northern Virginia
)
[latitude] => 38.91971111
[longitude] => -77.2259265
[phoneNumber] => 703-893-9005
)
)
)
)
)
You're telling json_decode() to give you an array but then you try to access its values like an object. Either return an object...
$response = json_decode(file_get_contents($file));
...or access those values using array syntax:
foreach ($response as $mydeal)
{
$category = $mydeal['category']['name'];
$title = $mydeal['websiteTitle'];
$finePrint = $mydeal['finePrint'];
$imageURL = $mydeal['imageURL'];
$merchant = $mydeal->merchant['displayName'];
$streetaddress1 = $mydeal['redemptionLocations']['addressStreet1'];
}
Related
I'm trying to find out in a simple way to display a clean like this format
Having a hard time to spread the data in this associative array got this from an API
Array (
[wind] => Array (
[speed] => 5
[direction] => North West
[directionDegrees] => 310
[unit] => KT
)
[visibility] => Array (
[mainVisibility] => 10SM
)
[clouds] => Array (
[0] => Array (
[height] => 25000
[quantity] => few
)
)
[cavok] =>
[remark] => automated station with a precipitation discriminator sea level pressure of 1021.7 HPa hourly temperature of 17.2°C and dew point of -1.1°C
[day] => 6
[time] => 22:52:00
[airport] => Array (
[name] => Hartsfield Jackson Atlanta International Airport
[city] => Atlanta
[country] => Array (
[name] => United States
)
[iata] => ATL
[icao] => KATL
[latitude] => 33.6367
[longitude] => -84.428101
[altitude] => 1026
[timezone] => -5
[dst] => A
)
[message] => KATL 062252Z 31005KT 10SM FEW250 17/M01 A3017 RMK AO2 SLP217 T01721011
[station] => KATL
[temperature] => 17
[dewPoint] => -1
[altimeter] => 1021
[nosig] =>
[auto] =>
[amendment] =>
[nil] =>
[corrected] =>
[cancelled] =>
)
I'm not good at programming as this is our assignment from our school I'm looking at to loop the array but I can't seem to find a way how to do it.
You can use this parser source code and make your own solution on the base
https://github.com/SafranCassiopee/php-metar-decoder
or simple way to get field
$arr = '$yourDataArrayHere$';
$metarRw = $arr['message']
echo 'Metar message '.$metarRw;
$airportName = $arr['airport']['name']
echo 'Airport name '.$airportName;
etc.
How i will make a this array value converted into a string for enable me to insert it to the database.
$myArray = Array
(
[0] => Array
(
[code] => 1
[name] => Array
(
[content] => Ohtels Villa Dorada
)
[description] => Array
(
[content] => This hotel is located about 150 metres from the fine sandy beach. The lively centre of Cambrils is approximately 10 km away and can be easily reached by the public bus services. There is a stop for public transport right in front of the hotel. The immediate vicinity offers a diverse range of shopping and entertainment facilities including boutiques, restaurants and bars. This hotel comprises a total of 260 rooms spread over 5 floors. Dining options include a café, a bar and an air-conditioned buffet restaurant with highchairs for infants. The tastefully decorated, cosy rooms come with a balcony and satellite TV.
)
[countryCode] => ES
[stateCode] => 43
[destinationCode] => SAL
[zoneCode] => 10
[coordinates] => Array
(
[longitude] => 1.152529
[latitude] => 41.068407
)
[categoryCode] => 3EST
[categoryGroupCode] => GRUPO3
[chainCode] => OHTEL
[accommodationTypeCode] => HOTEL
[boardCodes] => Array
(
[0] => BB
[1] => AI
[2] => HB
[3] => FB
[4] => RO
)
[segmentCodes] => Array
(
[0] => 37
)
[address] => Array
(
[content] => Carrer Del Vendrell,11
)
[postalCode] => 43840
[city] => Array
(
[content] => SALOU
)
[email] => comercial#ohtels.es
[license] => HT-000473
[web] => http://www.ohtels.es/
[lastUpdate] => 2019-03-14
[S2C] => 4*
[ranking] => 96
)
[1] => Array
(
[code] => 1
[name] => Array
(
[content] => Sample
)
[description] => Array
(
[content] => This hotel is located about 150 metres from the fine sandy beach. The lively centre of Cambrils is approximately 10 km away and can be easily reached by the public bus services. There is a stop for public transport right in front of the hotel. The immediate vicinity offers a diverse range of shopping and entertainment facilities including boutiques, restaurants and bars. This hotel comprises a total of 260 rooms spread over 5 floors. Dining options include a café, a bar and an air-conditioned buffet restaurant with highchairs for infants. The tastefully decorated, cosy rooms come with a balcony and satellite TV.
)
[countryCode] => ES
[stateCode] => 43
[destinationCode] => SAL
[zoneCode] => 10
[coordinates] => Array
(
[longitude] => 1.152529
[latitude] => 41.068407
)
[categoryCode] => 3EST
[categoryGroupCode] => GRUPO3
[chainCode] => OHTEL
[accommodationTypeCode] => HOTEL
[boardCodes] => Array
(
[0] => BB
[1] => AI
[2] => HB
[3] => FB
[4] => RO
)
[segmentCodes] => Array
(
[0] => 37
)
[address] => Array
(
[content] => Carrer Del Vendrell,11
)
[postalCode] => 43840
[city] => Array
(
[content] => SALOU
)
[email] => comercial#ohtels.es
[license] => HT-000473
[web] => http://www.ohtels.es/
[lastUpdate] => 2019-03-14
[S2C] => 4*
[ranking] => 96
)
)
i want all of the value of the $myArray would be inserted to the database
But also i used foreach loop to store it to a $variable and i will just concatinate the value into the query.
INSERT INTO test(code,contents) VALUES $variable;
Here is what am i doing.
$hotel_content = '';
foreach($myArray as $content)
{
$hotel_content .= "(".$content['code'].",".json_encode($content)."),";
}
$hotel = "INSERT INTO test(code,contents) VALUES ".rtrim($hotel_content,",").';';
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
if (mysqli_query($conn, $hotel) )
{
echo "You have successfully inserted the data.";
}
else
{
echo "Error: " . $hotel . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
Way 1:
You can insert full array by converting it to sting. So you can use PHP serialize function before insert.
$serialized_data = serialize($myarray);
then user $serialized_data into your insert query.
Ref: https://www.php.net/manual/en/function.serialize.php
Note you've to unserialize it when you'll use this data. So after retrieving from database unserialize it by unserialize() function.
Another way: you can use json_encode() function to store array. and you'll also need to use json_decode() when/where you'll use this data.
Ref: https://www.php.net/manual/en/function.json-encode.php
Define table column as longText
like this
$table->longText('column_name');
Then save data into it as JSON STRING
$value = json_encode($myArray);
So I'm working with an API for vehicles, and I am running into a wall and hoping to get some input from those with more experience with this... I'll start by showing an example of the data I get back from an API call.
Array
(
[make] => Array
(
[id] => 200003644
[name] => Chrysler
[niceName] => chrysler
)
[model] => Array
(
[id] => Chrysler_200
[name] => 200
[niceName] => 200
)
[engine] => Array
(
[equipmentType] => ENGINE
[availability] => USED
[cylinder] => 6
[size] => 3.6
[configuration] => V
[fuelType] => flex-fuel (unleaded/E85)
[horsepower] => 295
[type] => flex-fuel (FFV)
[code] => ERB
[rpm] => Array
(
[horsepower] => 6350
[torque] => 4250
)
[valve] => Array
(
[gear] => double overhead camshaft
)
)
[transmission] => Array
(
[equipmentType] => TRANSMISSION
[availability] => USED
[transmissionType] => AUTOMATIC
)
[drivenWheels] => front wheel drive
[numOfDoors] => 4
[options] => Array
(
[0] => Array
(
[category] => Safety
[options] => Array
(
[0] => Array
(
[id] => 200741607
[name] => SafetyTec
[description] => Adaptive Cruise Control with Stop & Go; Advanced Brake Assist; Automatic high beam control; Blind Spot and Cross Path Detection; Full Speed Forward Collision Warning Plus; Lane Departure Warning Plus; Parallel and Perpendicular Park Assist with Stop; Rain sensitive windshield wipers
[equipmentType] => OPTION
[availability] => All C/All C Platinum
)
)
)
[1] => Array
(
[category] => Package
[options] => Array
(
[0] => Array
(
[id] => 200741480
[name] => Quick Order Package 26N (Fleet)
[description] => Vehicle with standard equipment
[equipmentType] => OPTION
[availability] => All C
)
[1] => Array
(
[id] => 200741610
[name] => Premium Group
[description] => 115V auxiliary power outlet; Exterior mirrors with memory; Heated 2 tone leather steering wheel; Luxury door trim panel; Premium leather trimmed ventilated front seats with leather seat cushion; Radio/driver seat/Climate control with memory; Real wood/bronze chrome interior accents
[equipmentType] => OPTION
[availability] => All C/All C Platinum
)
[2] => Array
(
[id] => 200741715
[name] => Premium Lighting Group
[description] => HID headlamps with LED daytime running lights; LED fog lamps
[equipmentType] => OPTION
[availability] => All S/All C
)
[3] => Array
(
[id] => 200741805
[name] => Navigation And Sound Group I
[description] => 506 watt amplifier; SiriusXM traffic with 5-year of included service; Travel Link Service with 5-year of included service; 9 amplified speakers with subwoofer; GPS navigation; HD radio; Uconnect 8.4AN AM/FM/SiriusXM/Hard disc drive/Bluetooth/Navigation
[equipmentType] => OPTION
[availability] => All C
)
)
)
)
So if I have this data stored in a variable called $data for example, I can do something like this and it works:
foreach ($data['options'] as $options) {
echo $options['category'];
}
That will return me "Safety", and "Package".
However, if I wanted to get the vehicle's make and I do something like this:
foreach ($data['make'] as $make) {
echo $make['name'];
}
It just returns me the value : Cc (Upper case C from the make name, and lowercase c from the make niceName). Why is it doing this? What am I doing wrong?
Thank you!
There's only one 'make', so I think you just want this (no loop):
echo $data['make']['name'];
Every element of $data['make'] is a string (maybe integer), but not an array as every element of $data['options']. So, you can't use [] notation in case of $data['make'].
Just:
foreach ($data['make'] as $make) {
echo $make;
}
will do what you need.
I have a multidimensional php array which I am trying to printout in json format
This is the array
Array ( [0] => Array ( [name] => Zeninjor Enwemeka [title] => At Boston Forum, Federal And Local Officials Discuss Region�s Transportation Future [published] => 2015-10-14 12:22:00 ) [1] => Array ( [name] => Zeninjor Enwemeka [title] => Boston�s Transportation Future? City Releases Report Detailing Public�s Transit Goals [published] => 2015-10-09 09:17:00 ) [2] => Array ( [name] => Ryan caron King [title] => Sen. Murphy Seeks Feedback From �Fed Up� Car Commuters [published] => 2015-10-15 16:25:00 ) [3] => Array ( [name] => patrick skahill [title] => Solar Installations Skyrocket, But Connecticut Consumers Still Need to Do Their Homework [published] => 2015-10-15 09:12:00 ) )
I have tried this but it did not work:
print_r($output_result);
$output = array();
foreach($output_result as $v) {
$output[key($v)] = current($v);
}
echo json_encode($output);
I have the below array containing arrays and arrays. This is just one entry; imagine now that I have 20 sources and each source contains at least 10 entries like the one below. This is a nightmare I want to solve.
Can anyone advice on how I can parse this efficiently in PHP and be able to get each of the values to be able to insert them into a DB for further processing!! Thank you.
Array (
[id] => id
[direction] => ltr
[updated] => 1407220315278
[title] => Syria | The Guardian
[alternate] => Array ( [0] => Array (
[href] => href
[type] => text/html ) )
[continuation] => 147a4ddf48e:28d98:bda086f
[items] => Array ( [0] => Array (
[keywords] => Array (
[0] => Global development
[1] => Refugees
[2] => Syria
[3] => Middle East and North Africa
[4] => World news
[5] => UK news
[6] => Scotland
[7] => Conflict and development
[8] => Immigration and asylum )
[fingerprint] => 47075b4f
[originId] => originId
[id] => Te6w3H2VbpKKFda+uYdqytnutphL/kktv0RL7gq9jjU=_147a4ddf48e:28d98:bda086f
[title] => A Syrian refugee in Scotland: 'I'm one of the lucky ones' video
[published] => 1407218400000
[crawled] => 1407220315278
[alternate] => Array (
[0] => Array (
[href] => href
[type] => text/html ) )
[author] => Produced by Claudine Spera and Ellie Violet Bramley
[origin] => Array (
[streamId] => streamId
[title] => Syria | The Guardian
[htmlUrl] => htmlUrl )
[summary] => Array (
[direction] => ltr
[content] => Ayman is one of about 3 million Syrian refugees living outside his homeland. After nine of his friends were killed in Damascus, Ayman used his student visa to flee to the UK, leaving his wife and twin boys behind. 'We didn't expect civil war in Syria, never, ever,' he says. But now, with the help of the Red Cross, the family are reunited and building a life in Edinburgh Continue reading... )
[visual] => Array (
[url] => imagUrl
[height] => 252
[width] => 600
[contentType] => image/jpeg )
[unread] => 1
[categories] => Array (
[0] => Array (
[id] => user/5312f2fe-1adc-476f-93da-8b1db5a63180/category/عربي
[label] => عربي ) )
[engagement] => 4 [engagementRate] => 0.33 ) ) )
If there are always the same keys in the array it should be relatively easy to iterate with something like this:
foreach($yourarray as $key1=>$item1){
//dosomething
if($key1=="alternate"){
foreach($item1 as $key2=>$item2){
//and so on
}
}
}
As to saving it in a database I admit its not easy and I am not that experienced with databases but if I were you I'd save them in multiple tables with "1 to n" references.