Foreach loop returning only last result - php

I need to format a YYYY-MM-DD date to output like "12 January 2020", I have got the date to output correctly, but the code will only output one of the five values that I want, I've obviously missed something.
I'm having an issue where the following code only outputs a single result:
function populate_dropdown($form){
//Reading posts for "Events" post type;
$posts = get_posts("post_type=el_events&orderby=date&order=asc&el_eventcategory=flo-talanoa&numberposts=-1");
//Creating drop down item array.
$items = array();
//Adding post dates titles to the items array
foreach($posts as $post)
$unformatteddate = $post->startdate;
$dateTime = DateTime::createFromFormat("Y-m-d", $unformatteddate);
$dateformatted = $dateTime->format('j F Y');
$items[] = array(
"value" => $dateformatted . ': ' . $post->location,
"text" => $dateformatted . ': ' . $post->location
);
//Adding items to field id 1.
foreach($form["fields"] as &$field)
if($field["id"] == 1){
$field["type"] = "select";
$field["choices"] = $items;
}
return $form;
}
If I replace:
$unformatteddate = $post->startdate;
$dateTime = DateTime::createFromFormat("Y-m-d", $unformatteddate);
$dateformatted = $dateTime->format('j F Y');
$items[] = array(
"value" => $dateformatted . ': ' . $post->location,
"text" => $dateformatted . ': ' . $post->location
);
With:
$items[] = array("value" => $post->startdate . ': ' . $post->location, "text" => $post->startdate . ': ' . $post->location);
The code outputs all five values (though with YYYY-MM-DD date format), what am I missing? I'm a novice when it comes to PHP.
Thanks in advance

You forgot to add {} in your foreach loop
foreach($posts as $post){
$unformatteddate = $post->startdate;
$dateTime = DateTime::createFromFormat("Y-m-d", $unformatteddate);
$dateformatted = $dateTime->format('j F Y');
$items[] = array(
"value" => $dateformatted . ': ' . $post->location,
"text" => $dateformatted . ': ' . $post->location
);
}
//Adding items to field id 1.
foreach($form["fields"] as &$field){
if($field["id"] == 1){
$field["type"] = "select";
$field["choices"] = $items;
}
}

You were missing the curly braces {} in foreach.

Related

Why is PHP Foreach Loop only extracting last item in the element of JSON Array?

I'm extracting data from a JSON file and have no problem getting all the items except for one because it is an array within the JSON array.
Here is a sample of the JSON array:
{
"items": [
{
"id": "12345",
"snippet": {
"publishedAt": "2015-07-25T02:43:39.000Z",
"channelTitle": "BuzzFeedVideo",
"tags": [
"celebrity",
"celebrities",
"seven",
"seven years",
"years",
"different",
"now",
"then",
"ariana grande",
"justin bieber",
"calvin harris",
"miley cyrus",
"abigail breslin",
"daniel radcliffe",
"neville longbottom",
"matthew lewis",
"buzzfeed",
"buzzfeedvideo",
"buzzfeedyellow",
"video"
],
"defaultAudioLanguage": "en"
},
"statistics": {
"viewCount": "700146",
"likeCount": "16847",
"dislikeCount": "596",
"favoriteCount": "0",
"commentCount": "1563"
}
}
]
}
I can get id, snippet:publishedAt, but when it comes to tags, only the last item in the tags array "video" is extracted with my foreach loop.
Here is my foreach loop:
$tags = $videosResponse['items'][0]['snippet']['tags'];
foreach($tags as $tag):
$keywords = $tag;
echo $keywords;
endforeach;
How do I get all the items within the JSON tags array starting from "celebrity" down to "video"?
UPDATE:
What I'm trying to do is update a php array file with the JSON data using file_put_contents.
Here is the structure I'm using.
$tags = $videosResponse['items'][0]['snippet']['tags'];
foreach($tags as $tag):
$keywords = strtolower(replace_utf8_chars($tag));
$new_array_line = " '" . $id . "' => array\n\t(\n\t'datetime' => '" . $publishedAt . "',\n\t'title' => '" . addslashes($title) . "',\n\t'description' => '" . addslashes($description) . "',\n\t'channel title' => '" . addslashes($channelTitle) . "',\n\t'tags' => '" . $keywords . "',\n\t'duration' => '" . $duration . "',\n\t'viewCount' => '" . $viewCount . "',\n\t'likeCount' => '" . $likeCount . "',\n\t'commentCount' => '" . $commentCount . "',\n\t'url' => '" . $url . "'\n\t),";
endforeach;
and then the array pop and file put contents code is just below the $new_array_line variable.
if(!array_key_exists($id, $videoids)) {
$id_content = file($videoids_file); // Parse file into an array by newline
$id_data = array_pop($id_content);
if (trim($id_data) == ');?>') {
$id_content[] = "\n" . ' // ' . $_SERVER['REMOTE_ADDR'] . ' | ' . date('M j, y h:i:s A') . "\n"; // Echo debug line
$id_content[] = $new_array_line;
$id_content[] = "\n".$id_data;
file_put_contents($videoids_file, implode($id_content));
}
return array('title' => $title, 'description' => $description, 'channelTitle' => $channelTitle);
}
If I end the foreach after this last part, then the first item in the tags array is output, but if I end the foreach before the if statement, then only the last item in the tags array is output.
Do I need some sort of time delay before the if statement is executed?
$new_array_line = need to by replaced by $new_array_line .= otherwise the foreach loop will keep overriding it when evaluating the next tag value until keeping the last one which is related to the 'video' tag.
never heared of endforeach...
When the JSON is valid, you should be able to access the array with:
$videosResponse['items'][0]['tags'];

How to create a SELECT element with an array of options using PHP? [duplicate]

This question already has answers here:
creating variable name by concatenating strings in php
(4 answers)
Closed 8 years ago.
Simple question, with im sure a simple answer, I just cant get it working!!
I have a function which will be passed one of 5 id's (for example "first", "second", ",third", "fourth" and "fifth").
Inside this function I want to refer to an array whose name is the id followed by _array (for example "first_array", "second_array" etc...)
How do I concatenate the id name passed to the function with the string "_array" ? I know how to do this in a string but not when referring to another variable!
To sum up i will have:
$i_d = "first" //passed to my function
$string = "_array"
and I want to link to an array called:
$first_array
EDIT
My code is the following:
$option_timescale = array ( "1"=>"Immediately",
"2"=>"1 Month",
"3"=>"2 Months",
"4"=>"3 Months",
"5"=>"4 Months",
"6"=>"5 Months",
"7"=>"6 Months",
"8"=>"No Timescale"
);
$option_bus_route = array ( "1"=>"1 minute walk",
"2"=>"5 minute walk",
"3"=>"10 minute walk",
"4"=>"No Bus Needed"
);
$option_train_stat = array( "1"=>"5 minute walk",
"2"=>"10 minute walk",
"3"=>"5 minute drive",
"4"=>"10 minute drive",
"5"=>"No Train Needed"
);
function select_box($k,$v){ //$k is the id and $v is the description for the select boxes label
$string = "option_"; //these two lines
$option_array =$string . $k; //are the troublemakers!
$buffer = '<select name="' . $k . '" id="' . $k . '">';
foreach ($option_array as $num=>$desc){
$buffer .= '<option value="' . $num . '">' . $desc . '</option>';
}//end foreach
$buffer .= '</select>';
$buffer .= '<label for="' . $k . '">' . $v . '</label>';
return $buffer;
}//end function
And the code which calls this function is:
function create_table($titles, $id) { //$titles is the relevant array from lists.php, $id is the id of the containing div
$select = array('timescale','bus_route','train_stat'); //'select' id list
$textarea = array('notes'); // 'textarea' id list
$buffer = '<div id="' . $id . '">';
foreach ($titles as $k=>$v) { //$k is the database/id/name $v is the description text
if (in_array($k,$select)){
$buffer .= select_box($k,$v);
}
else if (in_array($k,$textarea)){
$buffer .= text_box($k,$v);
}
else{
$buffer .= check_box($k,$v);
}
}
$buffer .= '</div>';
echo $buffer;
}
Add $ to eval the string.
$i_d = "first";
$string = "_array";
$myvar = $i_d . $string;
$$myvar = array('one','two','three');
print_r( $$myvar);

DOMDocument with Quotations in the load URL

I am displaying contents of an XML file of a search URL from Wordpress using domdocument. Everything works on a normal search url, but when I want the search to be 'exact match' of the phrase, which means I have to put double quotes around the keyphrase, it returns nothing. So how do I get it to work when adding the quotations as shown in the URL below...
$rss = new DOMDocument();
$rss->load('' . home_url() . '/?s="' . ucfirst($player_data->first_name) . '+' . ucfirst($player_data->last_name) . '"&post_type=post&feed=rss2');
$feed = array();
foreach ($rss->getElementsByTagName('item') as $node) {
$item = array (
'title' => $node->getElementsByTagName('title')->item(0)->nodeValue,
'desc' => $node->getElementsByTagName('description')->item(0)->nodeValue,
'link' => $node->getElementsByTagName('link')->item(0)->nodeValue,
'date' => $node->getElementsByTagName('pubDate')->item(0)->nodeValue,
);
array_push($feed, $item);
}
//foreach($item as $moment); {
if (!$item==NULL) {
for($x=0;$x<10;$x++) {
$woohoo = str_replace(' & ', ' & ', $feed[$x]['title']);
$goto = $feed[$x]['link'];
$timex = $feed[$x]['desc'];
$dibidy = date('l F d, Y', strtotime($feed[$x]['date']));
$str_view_player .= '<div><strong>'.$woohoo.'</strong></div>';
// $str_view_player .= '<small><em>Posted on '.$dibidy.'</em></small></p>';
// $str_view_player .= '<p>'.$timex.'</p>';
}
} else {
$str_view_player .= '' . ucfirst($player_data->first_name) . ' ' . ucfirst($player_data->last_name) . ' has not been mentioned yet - but he will soon, we are sure of it!';
}
Notice the quote marks after s= and before &post_type
Either replace your quotation marks with %22 or use urlencode():
$url = '' . home_url() . '/?s="' . ucfirst($player_data->first_name) . '+' . ucfirst($player_data->last_name) . '"&post_type=post&feed=rss2';
$url = urlencode($url);
$rss->load($url);

Group 'Today's Events' under single Date Header?

I am trying to parse a Google Calendar to use on our TV's to display 'Today's Events'.
While I am most of the way there thanks to the help of a friend, I wanted to see if somebody could help me the rest of the way.
The code below generates the calendar with all the information, but for EVERY entry it shows the date. Since they are all the same day, this is kind of frustrating and confusing when looking at it. I am nowhere near a programmer, but I can make sense of some things.
How would I group all Todays events under a single date heading?
Thanks in advance.
<?php
$confirmed = 'http://schemas.google.com/g/2005#event.confirmed';
$three_months_in_seconds = 60 * 60 * 24 * 28 * 3;
$three_months_ago = date("Y-m-d\Th:i:s", time() - $three_months_in_seconds);
$three_months_from_today = date("Y-m-d\Th:i:s", time() + $three_months_in_seconds);
$params = "?orderby=starttime&start-min=" . $three_months_ago . "&start-max=" . $three_months_from_today;
//$params = "?orderby=starttime&start-min=2012-12-01T05:48:47&start-max=2013-05-07T05:48:47&sortorder=a&singleevents=true&futureevents=true";
$params = "?orderby=starttime&sortorder=a&singleevents=true&futureevents=true";
$feed = "https://www.google.com/calendar/feeds/REDACTED%40gmail.com/private-REDACTED/full".$params;
$doc = new DOMDocument();
if (!$doc->load( $feed )) echo 'failed to load';
$entries = $doc->getElementsByTagName( "entry" );
foreach ( $entries as $entry ) {
$status = $entry->getElementsByTagName( "eventStatus" );
$eventStatus = $status->item(0)->getAttributeNode("value")->value;
if ($eventStatus == $confirmed) {
$titles = $entry->getElementsByTagName( "title" );
$title = $titles->item(0)->nodeValue;
$times = $entry->getElementsByTagName( "when" );
$startTime = $times->item(0)->getAttributeNode("startTime")->value;
$when = date( "D M j, Y", strtotime( $startTime ) );
$time = date("g:i A",strtotime($startTime));
$places = $entry->getElementsByTagName( "where" );
$where = $places->item(0)->getAttributeNode("valueString")->value;
print "<div class='row when'>$when</div>";
echo "<div class='row event'><span class='time'>$time</span><span class='title'>$title</span><span class='where'>$where</span></div>";
// print $where . "\n";
print "\n";
}
}
?>
Have an answer:
just change this:
print "<div class='row when'>$when</div>";
to this:
if ($old_when!=$when) print "<div class='row when'>$when</div>"; $old_when=$when;
and add
$old_when = null;
before the foreach

DB Array to expected javascript format

I am implementing Highcharts in my application. It needs data in specific format.
The data in my table is as follows
The javascript needs data in below format
When I var_dump my x_axis array and y_axis array, I get below result
Which php functions should I use to format my array elements and pass to that JavaScript in that format?
data:[
[<? echo PHP_some_function(" ' ", x_axis) ?>, <? echo (y_axis) ?>] //quotes for x, no quotes for y value
] //Moreover it should run for all the values in x_axis and y_axis
I need some logic here..
My final graph would look like
The problem is your query.
It should be like the following.
SELECT x_axis, y_axis FROM yourTableName;
This way you'll get exactly the format that Highcharts needs. You just have to insert it inside an array.
Assuming:
$x_axis = array('Safari', 'Opera', 'Firefox', 'IE', 'Chrome', 'Others');
$y_axis = array(10, 6, 40.5, 20, 10.6, 0.5);
This should work:
$data = array();
$length = count($x_axis);
for ($i = 0; $i < $length; $i++) {
$data[] = array($x_axis[i], $y_axis[i]);
}
[<? echo "'". json_encode($x_axis). "', " . json_encode($y_axis) ?>]
Demo: http://codepad.org/G5JAtXWu
Nix that I was confused.
What you want to do is this:
foreach($x_axis as $key=>$x) {
echo "['" . $x . "', " . $y_axis[$key] . "]";
}
Demo: http://codepad.org/SKNk1VaX
To wrap it all up:
$d = array();
foreach($x_axis as $key=>$x) {
$d[] = "['" . $x . "', " . $y_axis[$key] . "]";
}
echo json_encode($d);
Demo: http://codepad.org/KhofwXCi
probably array combine and than json encode and replace? just in case for diversity;)
<?php
$x_axis = array(
'Safari', 'Opera', 'fireFox'
);
$y_axis = array(
10, 30.4, 50
);
$keyFilled = array_combine($x_axis, $y_axis);
arsort($keyFilled);
$jsonData = json_encode($keyFilled);
$jsonDataReplaced = str_replace(array(',', '{', '}', ':'), array('],[', '[', ']', ','), $jsonData);
echo '<pre>';
var_dump('['.$jsonDataReplaced.']');
?>
output is:
string(45) "[["fireFox",50],["Opera",30.4],["Safari",10]]"
http://phpfiddle.org/main/code/jq4-cgb

Categories