Getting array value - php

My debugging output below
Array (
[0] => Array (
[re_text_field_id] => No posts to display
[re_textarea_field_id] => boring jokes
[re_image_field_id] => Array (
[id] => 6
[src] => http://localhost/project/wp-content/uploads/2014/02/bg1.gif
)
) [1] => Array (
[re_text_field_id] => fuck it
[re_textarea_field_id] => I feel dumb for asking, but how on earth would i go about using the repeatable fields in a way which outputs the fields needed
[re_image_field_id] => Array (
[id] => 4 [src] => http://localhost/project/wp-content/uploads/2014/02/bg-gradient1.png
)
)
)
To get text field I used
$options = get_option('demo_options')
$slides = $options['re_'];
foreach ($slides as $slide) {
echo $slide['re_textarea_field_id'];
}
But I am unable to get image path somewhat like this way
echo $slide['re_image _field_id'];

Try this, to retrive the path of the image. Need to add ['src']
echo $slide['re_image_field_id']['src'];

Related

array index changing into string [name] not number

I have form (display.php) that will get multiple selected option from user. Then this selected option will be formatted to another page (page.php). The problem occur when I try to display those multiple selected option. The array index are changing into string [name]!
Array ( [0] => 3204120006 [1] => 3204120011 [2] => 3204120010 [3] => 3204120009 )
Array ( [name] => BIRU ) Array ( [name] => BOJONG ) Array ( [name] => MAJAKERTA ) Array ( [name] => MAJALAYA )
Here the code of above display.
<?php
if (isset($_POST["desas"])) {
$ddes=$_POST["desas"];
print_r ($ddes);
foreach ( $ddes as $iddesa ) {
$namadesa=mysql_query("SELECT name FROM villages WHERE id='$iddesa' ");
if ($namadesa) {
$datadesa = mysql_fetch_assoc($namadesa);
print_r($datadesa);
}
} else
$datadesa="";
}
?>
My question is how to change ([name]=>BIRU),([name]=>BOJONG) into index ([0]=>BIRU),([1]=>BOJONG) etc on those array? or something missing in mysql fetch?
you can use array_values. reference: https://secure.php.net/manual/en/function.array-values.php
$datadesa = array_values(array_values);

PHP Nested foreach with Key

I have been trying to work this out for two days now and am hitting a brick wall. I have a skyscanner array that has flight itineraries where I have the flight
Leg - being Itineraries -> OutboundLegId -
and also the legs which shows the flight number - being
Legs -> FlightNumbers -> FlightNumber.
What I am trying to achieve is to display the Itinerary and then join the Flight Number on to that. But no matter what I try I cannot get this to work. I have read all about Keys on here and tried loads of examples but am coming up with nothing. Can someone point me in the right direction please?
Example arrays below
[Itineraries] => Array
(
[0] => Array
(
[OutboundLegId] => 13542-1610140610-29-0-13445-1610141240
[InboundLegId] => 13445-1610211340-29-0-13542-1610211640
[PricingOptions] => Array
(
[0] => Array
(
[Agents] => Array
(
[0] => 2174187
)
[QuoteAgeInMinutes] => 31
[Price] => 200.98
[DeeplinkUrl] => http://partners.api.skyscanner.net/apiservices/deeplink/v2?_cje=5JlLCgyPUKY0hT8T0Ybh6dL0Xf0htAiHTFX7RU79eeI3XvrsxvEqP1QUJAoHiHRd&url=http%3a%2f%2fwww.apideeplink.com%2ftransport_deeplink%2f4.0%2fUK%2fen-gb%2fGBP%2fcook%2f2%2f13542.13445.2016-10-14%2c13445.13542.2016-10-21%2fair%2fairli%2fflights%3fitinerary%3dflight%7c-32294%7c1152%7c13542%7c2016-10-14T06%3a10%7c13445%7c2016-10-14T12%3a40%2cflight%7c-32294%7c1153%7c13445%7c2016-10-21T13%3a40%7c13542%7c2016-10-21T16%3a40%26carriers%3d-32294%26passengers%3d1%2c0%2c0%26channel%3ddataapi%26cabin_class%3deconomy%26facilitated%3dfalse%26ticket_price%3d200.98%26is_npt%3dfalse%26is_multipart%3dfalse%26client_id%3dskyscanner_b2b%26request_id%3d3bc96bda-fd7c-403a-b841-2ccc3c26071d%26commercial_filters%3dfalse%26q_datetime_utc%3d2016-09-29T08%3a18%3a27
)
[Legs] => Array
(
[0] => Array
(
[Id] => 13542-1610140610-29-0-13445-1610141240
[SegmentIds] => Array
(
[0] => 1
)
[OriginStation] => 13542
[DestinationStation] => 13445
[Departure] => 2016-10-14T06:10:00
[Arrival] => 2016-10-14T12:40:00
[Duration] => 270
[JourneyMode] => Flight
[Stops] => Array
(
)
[Carriers] => Array
(
[0] => 105
)
[OperatingCarriers] => Array
(
[0] => 105
)
[Directionality] => Outbound
[FlightNumbers] => Array
(
[0] => Array
(
[FlightNumber] => 1152
[CarrierId] => 105
)
)
)
Assuming this is one big array and its called $data you can nest a couple of foreach loops.
I use foreach loops as I assume there are cases where this data structure get more complex than the one you show
foreach ( $data['Itineraries'] as $itin ) {
foreach ( $data['Legs'] as $legs) {
if ($legs['Id'] == $itin['OutboundLegId']) {
// we matched the itinerary with a leg
echo $legs['OutboundLegId'] . ' ' . $legs['FlightNumbers'][0]['FlightNumber'];
}
}
}
Use it as draft. Can't perform function without feedback.
Put proper arrays instead of {YOUR-ARRAY-WITH-LEGS} and {YOUR-ARRAY-WITH-ITINERARIES}
$sortedLegs = array_column('Id', {YOUR-ARRAY-WITH-LEGS});
$joinedArray = array_map(function($itinerary) use($sortedLegs){
if(array_key_exists($itinerary['OutboundLegId'],$sortedLegs)) {
$itinerary['legs'] = $sortedLegs[$itinerary['OutboundLegId']];
}
return $itinerary;
},{YOUR-ARRAY-WITH-ITINERARIES});

Iterate through multidimensional PHP array and output values

I'm having a real headache trying to iterate through an array and output elements. Using the array structure below I want to be able to output each instance of partname.
The following loop outputs the first instance of partname. I can't seem to adapt it to loop through all instances within the array. I'm sure I'm missing something basic.
foreach($ItemsArray['assignments'] as $item) {
$partname = $item['grades'][0]['partname'];
}
Array
(
[assignments] => Array
(
[0] => Array
(
[assigntmentid] => 5101
[grades] => Array
(
[0] => Array
(
[id] => 5101
[name] => Advanced AutoCad
[partid] => 6601
[partname] => Draft
[userid] => 82069
[grade] => 53
[courseid] => 6265
[fullname] => Computer Aided Design
)
)
)
[1] => Array
(
[assigntmentid] => 5101
[grades] => Array
(
[0] => Array
(
[id] => 5101
[name] => Advanced AutoCad
[partid] => 6602
[partname] => Final
[userid] => 82069
[grade] => 35
[courseid] => 6265
[fullname] => Computer Aided Design
)
)
)
)
)
Instead of just coding by slapping the keyboard. Write down what your function needs to do. In english (or whatever language you prefer). This would be something like:
Foreach assignment, loop over all grades and store the partname of
that grade into an array.
And then code it:
function getPartnames($assignments) {
$partNames = array();
foreach ($assignments as $assignment) {
foreach($assignment['grades'] as $grade) {
$partNames[] = $grade['partname'];
}
}
return $partNames;
}
So what did I do? I simply translated english to code.
Some few more tips: Use variables names that make sense. $item; $ItemArray; ... don't make sense. They tell me nothing
use an extra foreach in your loop:
foreach($ItemsArray['assignments'] as $item) {
foreach($item['grades'] as $grade) {
echo $grade['partname'];
}
}

How to pull out certain value using php and this output

I've come across a weird scenario I do not know how to code around. I'm creating a JSON API for a wordpress site. I'm using the Connections plugin and trying to pull out the "original" image filename. The output of my sql command is this:
{
["options"]=>
string(396) "a:4:{s:5:"entry";a:1:{s:4:"type";s:12:"organization";}s:5:"group";a:1:{s:6:"family";a:0:{}}s:4:"logo";a:2:{s:6:"linked";b:0;s:7:"display";b:0;}s:5:"image";a:3:{s:6:"linked";b:1;s:7:"display";b:1;s:4:"name";a:4:{s:9:"thumbnail";s:25:"invoicelogo_thumbnail.jpg";s:5:"entry";s:21:"invoicelogo_entry.jpg";s:7:"profile";s:23:"invoicelogo_profile.jpg";s:8:"original";s:24:"invoicelogo_original.jpg";}}}"
}
}
I'm using the following command to acquire that:
querystr = "SELECT options FROM {$wpdb->prefix}connections WHERE id= '{$_GET['companyID']}'";
$options = $wpdb->get_results($querystr);
I'm not sure how to pull out the "original" part of this code though as it's not all that organized. Any help would be appreciated.
What you are seeing is the results of a php serialize call
To get at the original name just do this.
$decodedOptions = unserialize($options);
$original = $decodedOptions["image"]["name"]["original"];
Hope that helps
As a side note the deserialized data looks like
Array
(
[entry] => Array
(
[type] => organization
)
[group] => Array
(
[family] => Array
(
)
)
[logo] => Array
(
[linked] =>
[display] =>
)
[image] => Array
(
[linked] => 1
[display] => 1
[name] => Array
(
[thumbnail] => invoicelogo_thumbnail.jpg
[entry] => invoicelogo_entry.jpg
[profile] => invoicelogo_profile.jpg
[original] => invoicelogo_original.jpg
)
)
)

Ordering Array by value

I'm pulling in a list of my vimeo albums using the Vimeo API and the looping three times through the array to get to the albums. It works fine.
My question is, I'm isolating the date, so how can I create a new array and sort it by the date?
While where at it, is there a way to jump to the third level of a multi-dimensional array?
$albums=$vimeo->call('vimeo.albums.getAll', array('user_id' => $myUserId));
$albums_array=object_2_array($albums);
foreach($albums_array as $album_array_two){
foreach($album_array_two as $album_array_three){
foreach($album_array_threeas $album){
if(stristr($album['title'],'conference')){
$title=$album['title'];
$description=$album['description'];
$date=stristr($album['description'],'.',true);
$year_comma=stristr($date,',');
$year=ereg_replace("[^0-9]", "", $year_comma);
$url_title='http://www.psfk.com/events/'.str_replace( " ", "-", strtolower($title));
$url=''.$title.'';
$thumb=$album['thumbnail_video']['thumbnails']['thumbnail'][1]['_content'];
echo '<li class="album">';
echo '<img src="'.$thumb.'" alt="'.$title.'" />';
echo '<div class="info">';
echo '<h2>'.$url.'</h2>';
echo $description.'<br />';
echo 'View...';
echo '</div></li>';
}
}
}
}
Sample of the array returning one item:
Array (
[generated_in] => 0.0828
[stat] => ok
[albums] => Array (
[on_this_page] => 7
[page] => 1
[perpage] => 50
[total] => 7
[album] => Array (
[0] => Array (
[id] => 1690236
[title] => Interviews
[description] =>
[created_on] => 2011-09-10 21:43:49
[total_videos] => 1
[url] => Array (
[0] => http://vimeo.com/album/1690236
)
[video_sort_method] =>
[thumbnail_video] => Array (
[id] => 28825158
[owner] => 718882
[title] => Where Inspiration Comes From [thumbnails] => Array (
[thumbnail] => Array (
[0] => Array (
[height] => 75
[width] => 100
[_content] => http://b.vimeocdn.com/ts/192/593/192593029_100.jpg
)
)
)
)
)
)
)
)
In order to sort by date, you can use the php_function array_multisort(). There is a good example on that page that I think shows what you need. I'll try to provide a better example using your data. Suppose after looping through your albums you end up with an array $myAlbums that looks like this:
Array (
[0] => Array(
[title] => My Title
[description] => some description
[date] 01-05-2011
)
[1] => Array(
.......
)
In order to sort this by date, you could do the following (taken from the example on the php page)
<?php
// Obtain a list of columns
foreach ($myAlbums as $key => $row) {
$date[$key] = $row['date'];
}
// Sort the data with volume descending, edition ascending
// Add $myAlbums as the last parameter, to sort by the common key
array_multisort($date, SORT_DESC, $myAlbums);
?>
Then you can print_r($myAlbums); and you should see that it is sorted. You might have to change the SORT_DESC flag depending on what formate your dates are in. I can't really explain HOW this works, because I'm still trying to figure it out myself... but I think it is what you need.

Categories