Convert Array to html table in php - php

I have an array generated by an API i use a cpanel hosting with php 5.6.
I tried a lot of combination but is not working
The array are generated by emag marketplace api.
The code looks like
Array
(
[isError] =>
[messages] => Array
(
)
[results] => Array
(
[0] => Array
(
[vendor_name] => WISE COMPUTER SRLD
[id] => 2003677675
[parent_id] =>
[date] => 2017-05-21 10:55:18
[payment_mode] => RAMBURS
[payment_mode_id] => 1
[delivery_mode] => CURIER RO
[observation] =>
[status] => 4
[payment_status] => 0
[customer] => Array
(
[id] => 994041
[mkt_id] => 994041
[name] => Cristina Manuela Dancas
[company] => Cristina Manuela Dancas
[gender] =>
[phone_1] => 0743073616
[phone_2] =>
[phone_3] =>
[registration_number] =>
[code] =>
[email] =>
[billing_name] =>
[billing_phone] =>
[billing_country] => RO
[billing_suburb] => Bucuresti
[billing_city] => Sectorul 1
[billing_locality_id] => 2
[billing_street] => Str. Aviator Sanatescu nr. 57, parter, Ap1
[billing_postal_code] =>
[shipping_country] => RO
[shipping_suburb] => Bucuresti
[shipping_city] => Sectorul 1
[shipping_locality_id] => 2
[shipping_postal_code] =>
[shipping_contact] => Cristina Manuela Dancas
[shipping_phone] => 0743073616
[created] => 2017-05-21 10:55:19
[modified] => 2017-05-21 10:56:21
[bank] =>
[iban] =>
[legal_entity] => 0
[fax] =>
[is_vat_payer] => 1
[liable_person] =>
[shipping_street] => Str. Aviator Sanatescu nr. 57, parter, Ap1
)
I what to use php to convert in a HTML table.
Need some help. If you need more information please leave a message.

This is my quick solution to make a HTML table from a PHP array.
The essence is although, that a two-dimensional array, makes into a table that makes sense. Your array seems to be more complex, so converting into a useful table will probably take a bit more effort.
$data = array( array("ID","Firstname","Lastname","Phone"),
array("1","John","Jenkins","+91375953"),
array("2","Eduard","Kenny","+7244277"),
array("3","Anita","Beaumont","+427427427"),
array("4","Wanda","Wade","+274274247"),
array("4","Sarah","Colon","+835835"),
);
echo '<table border="1">';
foreach($data as $row) {
echo '<tr>';
foreach($row as $cell) {
echo '<td>'.$cell.'</td>';
}
echo '</tr>';
}
echo '</table>';

Related

Array_diff getting error Array to string conversion php

i want array_diff using this code i am also getting output but same time error occur
"Array to string conversion"
I am using codeigniter, i am getting post value in second array(listingdata) with method $this->input->post(); , but my first array getting some dynamic key and value then this two array diff give me output but some time getting error.
Please Help me
Any solution always welcome.
if(isset($_POST)){
foreach($_POST as $key => $value) {
$arr[$key] = $value; // making array
}
}
$result = array_diff($arr,$listingdata);
print_r($result);
print_r($arr);
print_r($listingdata);
My $arr array
Array
(
[itemTitle] => fdafdas
[subtitle] => fadsfdas
[quantity] => 12
[itemDescription] => fdas
[hide_ebay_id] => 89
[ebay_user] => Array
(
[0] =>
)
[ebay_category] => 2984
[e_sub_cat] => 20433
[e_second_child_sub_cat] => 117027
[e_third_child_sub_cat] =>
[ebay_upc] => 31231241341
[Brand] => Unbranded
[MPN] => Does_Not_Apply
[Model] => fsdf
[Country/Region_of_Manufacture] => Unknown
[listingType] => FixedPriceItem
[listingduration] => Days_5
[buy_it_now_price] => 20.00
[shippingtype] => Flat
[fshippingservice] => USPSPriorityFlatRateBox
[shippingservicecost] => 2.0
[shippingsac] => 3.0
[internationalhc] =>
[paypalemailaddress] => sam#jaff.in
[dispatchtimemax] => 3
[location] => CA
[ebaycountry] =>
[ebay_paypalemail] =>
[ReturnsAccepted] => ReturnsAccepted
[returnswithin] => Days_14
[refundoption] => MoneyBack
[shippingcostpaidbyoption] => Seller
[policydescription] => wqdewvfdgbfdggrbf
)
This is my another Array
Array
(
[itemTitle] => fdafdas
[subTitle] => fadsfdas
[categoryId] => 117027
[itemDescription] => fdas
[listingType] => FixedPriceItem
[listingDuration] => Days_5
[startPrice] =>
[buyItNowPrice] => 20.00
[quantity] => 12
[upc] => 31231241341
[paypalEmailAddress] => sam#jaff.in
[returnWithin] => Days_14
[RefundOption] => MoneyBack
[ShippingCostPaidByOption] => Seller
[returnsAccepted] => ReturnsAccepted
[shippingType] => Flat
[cshippingService] =>
[fshippingService] => USPSPriorityFlatRateBox
[dcPostalcode] =>
[ShippingServiceCost] => 2.0
[dshippingPackage] =>
[shippingHandlingcost] =>
[shippingServiceAdditionalCost] => 3.0
[currency] => USD
[country] =>
[location] => CA
[dispatchTimeMax] => 3
[pictureUrl] => Array
(
[0] => http://jaftech.in/ashprey/uploads/69.jpg
)
[policyDescription] => wqdewvfdgbfdggrbf
[internationalShipping] =>
[internationalShippingType] =>
[internationalShippingServiceCost] =>
[internationalshippingServiceAdditionalCost] =>
[cinternationalshippingService] =>
[finternationalshippingService] =>
[internationalShipToLocation] =>
[internationaloriginatingPostalCode] =>
[internationalshippingHandlingcost] =>
[ishippingPackage] => PackageThickEnvelope
[pid] => 89
)
This is because array_diff compares values after typecasting both compared values to string (see documentation notes).
Both of your arrays contain another array (ebay_user and second pictureUrl).
See this answer for recursive array_diff, which should work in your case.

iTunes Search Array

I am using a wrapper that makes it very simple to grab a search term and convert it into an array.
I am having trouble parsing this array. How do I create a foreach() loop to get the values from this array?
This is the simple function that is grabbing the search term and converting to an array. The print_r() simply shows me what is being returned.:
require_once (get_template_directory() . '/Classes/itunes.php');
function itunesSearch() {
$search_term = $_GET['s'];
$results = iTunes::search($search_term, array(
'country' => 'US'
))->results;
print_r($results);
}
For example, let's say I search for Adele. Here is the array that is being returned:
Array ( [0] => stdClass Object ( [wrapperType] => track [kind] => song [artistId] => 262836961 [collectionId] => 1051394208 [trackId] => 1051394215 [artistName] => Adele [collectionName] => 25 [trackName] => Hello [collectionCensoredName] => 25 [trackCensoredName] => Hello [artistViewUrl] => https://itunes.apple.com/us/artist/adele/id262836961?uo=4 [collectionViewUrl] => https://itunes.apple.com/us/album/hello/id1051394208?i=1051394215&uo=4 [trackViewUrl] => https://itunes.apple.com/us/album/hello/id1051394208?i=1051394215&uo=4 [previewUrl] => http://a1912.phobos.apple.com/us/r1000/170/Music6/v4/68/34/f1/6834f1f8-8fdb-4247-492a-c0caea580082/mzaf_3920281300599106672.plus.aac.p.m4a [artworkUrl30] => http://is5.mzstatic.com/image/thumb/Music6/v4/8c/91/5d/8c915d9b-d9e4-f735-1b91-81ca1b6e6312/source/30x30bb.jpg [artworkUrl60] => http://is5.mzstatic.com/image/thumb/Music6/v4/8c/91/5d/8c915d9b-d9e4-f735-1b91-81ca1b6e6312/source/60x60bb.jpg [artworkUrl100] => http://is5.mzstatic.com/image/thumb/Music6/v4/8c/91/5d/8c915d9b-d9e4-f735-1b91-81ca1b6e6312/source/100x100bb.jpg [collectionPrice] => 10.99 [trackPrice] => 1.29 [releaseDate] => 2015-11-20T08:00:00Z [collectionExplicitness] => notExplicit [trackExplicitness] => notExplicit [discCount] => 1 [discNumber] => 1 [trackCount] => 11 [trackNumber] => 1 [trackTimeMillis] => 295502 [country] => USA [currency] => USD [primaryGenreName] => Pop [radioStationUrl] => https://itunes.apple.com/station/idra.1051394215 [isStreamable] => )
[1] => stdClass Object ( [wrapperType] => track [kind] => song [artistId] => 262836961 [collectionId] => 420075073 [trackId] => 420075084 [artistName] => Adele [collectionName] => 21 [trackName] => Rolling in the Deep [collectionCensoredName] => 21 [trackCensoredName] => Rolling in the Deep [artistViewUrl] => https://itunes.apple.com/us/artist/adele/id262836961?uo=4 [collectionViewUrl] => https://itunes.apple.com/us/album/rolling-in-the-deep/id420075073?i=420075084&uo=4 [trackViewUrl] => https://itunes.apple.com/us/album/rolling-in-the-deep/id420075073?i=420075084&uo=4 [previewUrl] => http://a818.phobos.apple.com/us/r1000/115/Music/3d/fd/74/mzm.dqadcdcf.aac.p.m4a [artworkUrl30] => http://is5.mzstatic.com/image/thumb/Music/v4/cf/7e/47/cf7e47a8-bb18-9156-43d0-7591d0e0855e/source/30x30bb.jpg [artworkUrl60] => http://is5.mzstatic.com/image/thumb/Music/v4/cf/7e/47/cf7e47a8-bb18-9156-43d0-7591d0e0855e/source/60x60bb.jpg [artworkUrl100] => http://is5.mzstatic.com/image/thumb/Music/v4/cf/7e/47/cf7e47a8-bb18-9156-43d0-7591d0e0855e/source/100x100bb.jpg [collectionPrice] => 10.99 [trackPrice] => 1.29 [releaseDate] => 2011-02-22T08:00:00Z [collectionExplicitness] => notExplicit [trackExplicitness] => notExplicit [discCount] => 1 [discNumber] => 1 [trackCount] => 12 [trackNumber] => 1 [trackTimeMillis] => 228293 [country] => USA [currency] => USD [primaryGenreName] => Pop [radioStationUrl] => https://itunes.apple.com/station/idra.420075084 [isStreamable] => 1 ) ...
This is what I've tried, and several variations of this:
$results_thing = $results['stdClass']['Object'];
foreach ($results_thing as $result) {
echo $result['wrapperType'];
I am getting the error:
Warning: Invalid argument supplied for foreach()
Say that the $results holds the array you given above. Then the code for getting 'wrapperType'...
foreach($results as $result) {
$wrapper_type = $result->wrapperType;
}

Extract data from Array/Object in PHP?

First off, I'm new to PHP and coding in general, so this might be quite an obvious answer.
I'm currently working with the Strava API, and I'm trying to extract data from an Array/Object which is the result of the following API call:
$recentactivities = $api->get('athlete/activities', array('per_page' => 100));
which returns:
Array (
[1] => stdClass Object (
[id] => XXXX
[resource_state] => 2
[external_id] => XXXX
[upload_id] => XXXX
[athlete] => stdClass Object (
[id] => XXXX
[resource_state] => 1
)
[name] => Let\'s see if I can remember how to do this cycling malarkey...
[distance] => 11858.3
[moving_time] => 1812
[elapsed_time] => 2220
[total_elevation_gain] => 44
[type] => Ride
[start_date] => 2014-07-12T13:48:17Z
[start_date_local] => 2014-07-12T14:48:17Z
[timezone] => (
GMT+00:00
) Europe/London
[start_latlng] => Array (
[0] => XXXX
[1] => XXXX
)
[end_latlng] => Array (
[0] => XXXX
[1] => -XXXX
)
[location_city] => XXXX
[location_state] => England
[location_country] => United Kingdom
[start_latitude] => XXXX
[start_longitude] => XXXXX
[achievement_count] => 4
[kudos_count] => 1
[comment_count] => 0
[athlete_count] => 1
[photo_count] => 0
[map] => stdClass Object (
[id] => a164894160
[summary_polyline] => XXXX
[resource_state] => 2
)
[trainer] =>
[commute] =>
[manual] =>
[private] =>
[flagged] =>
[gear_id] => b739244
[average_speed] => 6.544
[max_speed] => 10.8
[average_cadence] => 55.2
[average_temp] => 29
[average_watts] => 99.3
[kilojoules] => 179.9
[device_watts] =>
[average_heartrate] => 191.2
[max_heartrate] => 200
[truncated] =>
[has_kudoed] =>
)
This repeats for the most recent activities.
I'm attempting to extract average_heartrate, which I can do for a single object using the following:
$recentactivities[1]->average_heartrate;
but I'd like to extract all instances of average_heartrate from the Array. I've tried to use a foreach statement, but to be honest, I have no idea where to start.
Any help would be much appreciated.
It's actually pretty simple you can indeed use a foreach loop:
foreach($myArray as $obj){
//$obj is an object so:
if(isset($obj->average_heartrate)){
echo $obj->average_heartrate;
}
}
With this code you iterate through your array with objects and save the wanted array within an array so you can work further with it.
$heartrateArray = array(); // create a new array
//iterate through it with an foreach
foreach($recentactivities as $activity){
// save the average_heartrate as a value under a new key in the array
$heartrateArray[] = $activity->average_heartrate;
}

How to echo an array value

I am fairly new to PHP and I am writing a PHP function that grabs an object from SOAP.
I found a code to convert it to an array but I can't manage to echo any data.
The array from print_r
Array
(
[Status] => Array
(
[Code] => 0
[Message] => OK
)
[Order] => Array
(
[OrderNumber] => 9334543
[ExternalOrderNumber] =>
[OrderTime] => 2014-07-15T15:20:31+02:00
[PaymentMethod] => invoice
[PaymentStatus] => Paid
[ShipmentMethod] => Mypack
[DeliveryStatus] => Delivered
[Language] => sv
[Customer] => Array
(
[CustomerId] => 13556
[CustomerNumber] =>
[Username] => admin
[Approved] => 1
[OrgNumber] => 9309138445
[Company] =>
[VatNumber] =>
[FirstName] => Jane
[LastName] => Doe
[Address] => Gatan
[Address2] =>
[Zip] => 1230
[City] => Staden
[Country] => Sweden
[CountryCode] => SE
[PhoneDay] => 84848474
[PhoneNight] =>
[PhoneMobile] =>
[Email] => mail#msn.com
[NewsLetter] =>
[OrgType] => person
[OtherDelivAddress] =>
[DelivName] =>
[DelivAddress] =>
[DelivAddress2] =>
[DelivZip] =>
[DelivCity] =>
[DelivCountry] =>
[DelivCountryCode] =>
)
[Comment] =>
[Notes] => 9063025471 UK/MA
[CurrencyCode] => SEK
[ExchangeRate] => 1
[LanguagePath] => se
[FreightWithoutVat] => 0
[FreightWithVat] => 0
[FreightVatPercentage] => 25
[PayoptionFeeWithoutVat] => 0
[PayoptionFeeWithVat] => 0
[PayoptionFeeVatPercentage] => 25
[CodWithoutVat] => 0
[CodWithVat] => 0
[CodVatPercentage] => 0
[DiscountWithoutVat] => 0
[DiscountWithVat] => 0
[DiscountVat] => 0
[TotalWithoutVat] => 4388
[TotalWithVat] => 5485
[TotalVat] => 1097
[PayWithoutVat] =>
[AffiliateCode] =>
[AffiliateName] =>
[OrderField] => Array
(
[0] => Array
(
[Name] => external_ref
[Value] => 43445
)
[1] => Array
(
[Name] => webshopid
[Value] => 423
)
[2] => Array
(
[Name] => webshopname
[Value] => Manuell
)
)
)
)
Non working code
echo $array[1][0]
I have tried different combos of indexes. I know how to return the values from the soap object but if I could do it this way it would be easier. It should work shouldn't it?
$array[1] is the second index of the array. the key of this array us "Status", this array contains a code and message
i assume you want to echo the message, you can do that with the following
echo $array[1]["Status"]["Message"];
You should use $array['Status']['Code'] , $array['Status']['Message'], $array['Order']['OrderNumber'], $array['Order']['Customer']['CustomerId'] and so on to display your data. It's an associative array so you need to use string keys and not numbers
try
$array['Order']['Customer']['LastName']
is my best guess without losing my sanity in that one line.
But for us to be sure please post the print_r($array) output
There are some way I always do this:
print_r($array);
And the other way is
$array[0]['Order']['LastName']
Try to access the arrays elements with the string keys, not the integer ones you are using:
echo $array['Order']['Customer']['Address'];
Another way you could see what is going on is by iterating through the array, and print out the keys and values:
foreach ($array as $key => $value)
echo "Key=$key value=$value<br>";

complicated multidimentional array process with foreach

im having a problem trying to process this array tried several different ways but none where right, here's the array
Array (
[search] => Array (
[response] => Array (
[errors] =>
[number_of_hotels] => 1 of 1
)
[lr_rates] => Array (
[hotel] => Array (
[hotel_ref] => 3116
[hotel_currency] => [U] => USD
[hotel_rooms] => Array (
[room] => Array (
[ref] => 6382
[type] => 1
[type_description] => Standard
[sleeps] => 8
[rooms_available] =>
[adults] => 8
[children] =>
[breakfast] => false
[dinner] => false
[description] =>
[alternate_description] =>
[rack_rate] => 82.01
[date] => 19/08/201220/08/201221/08/2012
[numeric_hotelcurrencyprice] => FullFullFull
[formatted_date] => 19 August 201220 August 201221 August 2012
[price] => FullFullFull
[hotelcurrencyprice] => FullFullFull
[numeric_price] => FullFullFull
[requested_currency] => GBPGBPGBP
[numeric_hotelcurrencyprice] => FullFullFull
[available_online] => false
[minimum_nights] => 1
[bed_type] =>
[cancellation_policy] =>
[cancellation_days] =>
[cancellation_hours] =>
[room_terms] =>
)
[room] => Array (
[ref] => 6382
[type] => 1
[type_description] => Standard
[sleeps] => 8
[rooms_available] =>
[adults] => 8
[children] =>
[breakfast] => false
[dinner] => false
[description] =>
[alternate_description] =>
[rack_rate] => 82.01
[date] => 19/08/201220/08/201221/08/2012
[numeric_hotelcurrencyprice] => FullFullFull
[formatted_date] => 19 August 201220 August 201221 August 2012
[price] => FullFullFull
[hotelcurrencyprice] => FullFullFull
[numeric_price] => FullFullFull
[requested_currency] => GBPGBPGBP
[numeric_hotelcurrencyprice] => FullFullFull
[available_online] => false
[minimum_nights] => 1
[bed_type] =>
[cancellation_policy] =>
[cancellation_days] =>
[cancellation_hours] =>
[room_terms] =>
)
)
[cancellation_type] => First Night Stay Chargeable
[cancellation_policy] => 2 Days Prior to Arrival
[CityTax] => Array (
[TypeName] =>
[Value] =>
[OptedIn] =>
[IsCityTaxArea] =>
)
)
)
)
)
ok i need to traverse the array and create a loop so for every instance of room it will repeat the process then i need to extract the data from room array and use it to populate rows in MySQL there will be multiple instances of room this is the code i have so far which prints the names and values in the room array but it only gets one of the room arrays what can i do to set it up to read them all and i am also thinking this is too many for-each but don't seem to be able to traverse down ['']['']['']...
or by just using the associative name.
foreach($arr['search'] as $lr_rates) {
foreach($lr_rates['hotel'] as $hotel) {
foreach($hotel['room'] as $field => $value){
print $field;print $value;
}
}
}
it mite also be worth mentioning the values in these arrays are always fluctuating
you don't have to use so much foreach loops in your script as it not looks good. this is an associative array.
you can simply access associate array by using its keys. do some google for it.you can find many scripts on this.
foreach($arr as $search) {
foreach($search as $lr_rates) {
foreach($lr_rates as $hotel) {
foreach($hotel as $hotel_rooms) {
print_r($hotel_rooms['room'])
}
}
}
}
EDIT: These many foreach loops are just to make understand how to reach to room. You can also get the result directly ofcourse.
print_r($arr['search']['lr_rates']['hotel']['hotel_rooms']['room']);

Categories