Pulling in fields through an array - php

I'm using a wordpress plugin names "Advanced Custom Fields".
Within the admin I have a select field where multiple choices can be selected.
So for example the admin will have the following selected....
/apples-category/ : Read More on apples
/pears-category/ : Read More on pears
/oranges-category/ : Read More on oranges
/peach-category/ : Read More on peaches
The first part which is the value (/apples-category/) will be used within a hyper link. The second part which is the label (Read More on apples) will be the anchor text.
I've put the following together which outputs the following correct labels but for some reason they all have the href (value) of the very last option (/peach-category/)
Read More on apples, Read More on pears, Read More on oranges, Read More on peaches
Here's my code and apologies if it looks obvious, I've just started out coding and still need assistance :)
Hope you can assist.
<?php
$labels = array();
$field = get_field_object('select_fruit');
$values = get_field('select_fruit');
foreach ($values as $value) {
$labels[] = $field['choices'][ $value ];
}
foreach ($labels as $k=>$label){
echo '<a href="'.$value.'" />'.strtoupper($label).'</a>'.($k == count($labels) - 1 ? '' : ', ');
}?>

Try this code:
<?php
$fruit_array = array();
$field = get_field_object('select_fruit');
if(!empty($field['value']))
{
foreach ($field['value'] as $value)
{
$fruit_array[$value]=$field['choices'][ $value ];
}
$cnt=0;
foreach ($fruit_array as $fruit_key=>$fruit_value)
{
echo '<a href="'.$fruit_key.'" />'.strtoupper($fruit_value).'</a>'.($cnt == count($fruit_array) - 1 ? '' : ', ');
$cnt++;
}
}
?>

Related

Start index numbering at 1 (not 0) with $key

I've got a wordpress shortcode, giving me an array of ids to build a list of links. Everything's fine so far. But now I'd like to number these links, so I use $key to output the index. Unfortunately numbering (within the span tag) starts with zero (0) and I can't figure a way to add + 1 to $key :(
function wp_ytlinks($atts){
extract(shortcode_atts(array( 'id' => 1 ), $atts));
echo '<div class="videonav">';
$value = explode(',', $id);
$index = 0;
foreach ($value as $key=>$att_id)
{
echo '<a class="yt-vid" id="yt-load" href="http://www.youtube.com/embed/' .
$att_id . '?rel=0" target="screen"><span>' . $key . '</span></a>';
}
};
add_shortcode('ytlinks', 'wp_ytlinks');
The Shortcode looks like this: [ytlinks id="J0Np2hn84Tc,cVHGLdZQgEw"]
Can s.o. please help?
OKay, I don't know, after an hour of stupid back and forth I tried something REALLY easy and it worked...
foreach ($value as $key=>$att_id) {
$nums = $key + 1;
...
Why do I have to post a question here to find such an easy solution?! Sorry guys...

Pull data from nested json loop php

Ok, I have been fighting this for two days now!! Here is my Json structure.
[
{
"uuid":"/random number==",
"meeting_number":7196503037,
"host_id":"random number",
"topic":"My's Personal Meeting Room",
"start_time":"2015-01-06T22:01:07Z",
"timezone":"America/Denver",
"duration":56,
"total_size":378080,
"recording_count":1,
"recording_files":[
{
"id":"long number",
"meeting_id":"/NS90bsSTLeGzo6cT0nwXw==",
"recording_start":"2015-01-06T22:01:09Z",
"recording_end":"2015-01-06T22:01:14Z",
"file_size":378080,
"play_url":"https://myurl"
}
]
},
I am trying to pull the Start Time from the top level array (which is named 'meetings') and the Play Url from the second level array (recording_files). I am using json_decode to decode the file into arrays.
I have tried many variations found on this site and nothing seems to get to the play url.
VARIATION 1
$aha = json_decode($response,true);
foreach ($aha['meetings'] as $key => $value){
foreach($key['recording_files'] as $subkey => $newvalue){
echo '<p>Time : '.$value['start_time'].'</p>
Recording<br>';
}}
This pulls an invalid argument in foreach.
VARIATION 2
foreach ($aha['meetings'] as $key => $value){
echo '<p>Time : '.$value['start_time'].'</p>
Recording<br>';
}
This pulls undefined index for play_url. As does the same code with the reference to ['recording_files'] placed before ['play_url']
VARIATION 3:
Then I tried giving up on the first level and just pulling data from the second level:
$aha = json_decode($response,true);
foreach ($aha['meetings']['recording_files'] as $key => $value){
echo '<p>Time : '.$value['recording_start'].'</p>
Recording<br>';
}
That gives me an undefined index on ['recording_files'] and a foreach error.
VARIATION 4.
$aha = json_decode($response,true);
foreach ($aha['meetings'] as $key => $value){
$link=$key['recording_files'];
echo '<p>Time : '.$value['start_time'].'</p>
Recording<br>';
}
This gets me the closest - no errors but no link. I presume that here the code is seeing the field but just not pulling the data from it...
Please help a newbie json person!!
If there is really an $aha['meetings'] (you don't show it), then use the value not the key in the second foreach:
foreach($aha['meetings'] as $value){
foreach($value['recording_files'] as $newvalue){
Final code that fixed it.
$aha = json_decode($response,true);
foreach ($aha['meetings'] as $key => $value){
echo '<p>Time : '.$value['start_time'].'</p>
Recording<br>';}
It was just a matter of finding the correct format for referencing the play_url piece.
Thank you so much to everyone!
Edit:
If your data looks like this :
$str = "{\"meetings\":[{
\"uuid\":\"/random number==\",
\"meeting_number\":7196503037,
\"host_id\":\"random number\",
\"topic\":\"My's Personal Meeting Room\",
\"start_time\":\"2015-01-06T22:01:07Z\",
\"timezone\":\"America/Denver\",
\"duration\":56,
\"total_size\":378080,
\"recording_count\":1,
\"recording_files\":[
{
\"id\":\"long number\",
\"meeting_id\":\"/NS90bsSTLeGzo6cT0nwXw==\",
\"recording_start\":\"2015-01-06T22:01:09Z\",
\"recording_end\":\"2015-01-06T22:01:14Z\",
\"file_size\":378080,
\"play_url\":\"https://myurl\"
}
]
}]}";
$json = json_decode($str);
$res = $json->{'meetings'};
foreach($res as $keys){
echo $keys->{'start_time'}."<br>";
foreach ($keys->{'recording_files'} as $data){
echo $data->{'play_url'}."<br>";
echo $data->{'recording_start'}."<br>";
}
}

Retrieve a value from an array and make a condition

I have the following code that I am using on WordPress:
if($terms && !is_wp_error($terms) ) {
$colors = array();
foreach ($terms as $term) {
$colors[] = '\'' . $term->slug . '\'';
}
}
print_r(array_values($thePack));
The variable $color now is a basic Array, which print_r displays like this:
Array (
[0] => 'white'
[1] => 'green'
)
I'd like to make a condition in order recognize whether the array has or not a specific value, for example:
if(in_array('white', $colors) {
echo "This is white";
}
However, it is not working at all, because the in_array does not recognize the value in the array!
How could I make the condition work?
Your array values (the color names) include single quotes, which you need to include when you search for a value:
if(in_array("'white'", $colors) {
// ...
}
Why not do something like this:
while(list($key, $value) = each($array)){
if($value == 'white'){
echo 'this is white';
}
}
The problem is you are escaping the color into the array. Instead of using
$colors[] = '\''.$term->slug.'\''
Just do
$colors[] = $term->slug
And when you output the slug to the web page or the database, then you escape it.

Stripslashes() on array

I have some problems using stripslashes() on array.
Here is my array :
$tabRegion = array(
1=>"Alsace",
2=>"Aquitaine",
3=>"Auvergne",
4=>"Basse-Normandie",
5=>"Bourgogne",
6=>"Bretagne",
7=>"Centre",
8=>"Champagne-Ardenne",
9=>"Corse",
10=>"Franche-Comté",
(...)
21=>"Provence-Alpes-Côte d'Azur",
22=>"Rhône-Alpes",);
In order to stripslash, I have adapted this PHP code :
foreach ($tabRegion as $key=>$region) {
$tabRegion[$key] = stripslashes($region);
}
After in the file, I generate URL with it for example :
if (file_exists('../region/$tabRegion[$region]/$fonction/messages/$lecturefichier (...)
But the fact is that the last value of the array is always selected ("Rhône-Alpes") by the code... I don't know why.
Do you have an idea? :)
Thank you !
You are using foreach loop then you have to generate url in that loop.
In that loop you will get each region value
$tabRegion = array(
1=>"Alsace",
2=>"Aquitaine",
3=>"Auvergne",
4=>"Basse-Normandie",
5=>"Bourgogne",
6=>"Bretagne",
7=>"Centre",
8=>"Champagne-Ardenne",
9=>"Corse");
foreach ($tabRegion as $key=>$region)
{
$tabRegion[$key] = stripslashes($region);
print "<br>".$region;
}
Output will be :
Alsace
Aquitaine
Auvergne
Basse-Normandie
Bourgogne
Bretagne
Centre
Champagne-Ardenne
Corse
So that,you have to insert following line in that for loop :
if (file_exists('../region/$tabRegion[$region]/$fonction/messages/$lecturefichier (...)
You are using $region variable in foreach loop and you should know that it is treated like any other variable in your script. So for example:
$fruit = 'Banana';
foreach(array('Tomato', 'Orange') as $fruit) {
echo $fruit;
}
echo $fruit; // it will output 'Orange';

Loop through foreach array

I'm having a problem looping through my array to get just one value each time. I want to gray only 1 value because I'm calling that value in jquery. I'm new and sorry if this is too basic but I've been trying for days, pulling my hair out!
$designslist = array('design1','design2','design3','design4');
$current_index = 0;
$current_id = current($designslist);
$next = $designslist[$current_index + 1];
foreach( $designslist as $value )
{
if( $value !== $next )continue;
$nexts = $next;
echo $nexts;
$current_index++;
}
Inside my html
next
calling the id with jquery
$('#design1').on('click',function() {
$('#web1').removeClass().addClass('big1');
});
foreach( $designslist as $value )
needs to be
foreach( $designslist as $i => $value )
$i is the array index
You can try array search
$tag = array_search($value, $designslist);
$nexts = $$designslist[$tag];
Ok, you seem to be mixing for with foreach using these "current_id" and "next" variables.
You can use this kind of foreach statement:
foreach ($designList as $key => $value) {
echo "The key of $value is $key";
}
As you want to return only unique values, you should use the "array_unique" function. Try this:
foreach (array_unique($designList) as $key => $value) {
echo "The key of $value is $key";
}
I know it's not related to the question, but, as you said you're new to this, there are some PHP tips you should follow.
You're mixing snake_case with camelCase in your variables. I recommend using camelCase, but it's up to you.

Categories