I'm stuck in my php script for a blog where I want to display the time and date for all the articles. I created a function but I don't know why it doesn't want to work:
function articles(){
global $bdd;
$articles = $bdd->query("SELECT id, titre, accroche, contenu, publication, image FROM articles");
$articles = $articles->fetchAll();
return $articles;
}
function formattage_date($publication){
$publication = explode(" ", $publication);
$date = explode("-", $publication[0]);
$heure = explode(":", $publication[1]);
$mois = ["", "janvier", "fevrier", "mars", "avril", "mai", "juin", "juillet", "août", "septembre", "octobre", "novembre", "decembre"];
$resultat = $date[2] . ' ' . $mois[$date[1]] . ' ' . $date[0] . ' à ' . $heure[0] . 'h' . $heure[1];
return $resultat;
}
When I want to use $mois, php says: Notice: Undefined index: 03 in C:\wamp\www\entertheletter.dev\fonctions\blog.php on line 18
Your problem is the following;
$mois[$date[1]]
The date string from the database is zerofilled if the value is below 10. So assume that the month is january (janvier), you get 01 instead of 1. When accessing the $mois array with that index, it is not able to find it because 01 is not a valid index.
To fix this, remove the first 0 if the date is zerofilled. Or just cast it to int like
$mois[(int)$date[1]]
you can try this function where i have added ltrim function in $mois array we have to converted 01 to 0 because array index start from 0,1,2 ...
so we have to remove 0 from 01.
function formattage_date($publication){
$publication = explode(" ", $publication);
$date = explode("-", $publication[0]);
$heure = explode(":", $publication[1]);
$mois = ["", "janvier", "fevrier", "mars", "avril", "mai", "juin", "juillet", "août", "septembre", "octobre", "novembre", "decembre"];
$resultat = $date[2] . ' ' . $mois[ltrim($date[1],0)] . ' ' . $date[0] . ' à ' . $heure[0] . 'h' . $heure[1];
return $resultat;
}
Related
I'm using laravel 5.8 and am trying to get a foreach to implode
foreach($stocks->currency as $currency)
{
$d1 = $currency->cost;
$d2 = $currency->currency->name;
$currencies = array(' ' . $d1 . ' ' . $d2);
echo implode("or", $currencies);
}
Is my code block
However, this returns the following :
clearly this lacks the "or" that the implode should add
Thank you in advance!
try something like
$currencies = [] // Create an empty array
foreach($stocks->currency as $currency)
{
$d1 = $currency->cost;
$d2 = $currency->currency->name;
$currencies[] = ' ' . $d1 . ' ' . $d2; // Add a new value to your array
}
echo implode("or", $currencies); // implode the full array and separate the values with "or"
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.
I have a simple html dom query which read informations from a football fixtures source, and I loading also a json source.
Here is my full code:
<?php
header('Content-Type: text/html; charset=utf-8');
ini_set("user_agent", "User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.60 Safari/537.17");
include_once('simple_html_dom.php');
ini_set('display_errors', true);
error_reporting(E_ALL);
$str = file_get_contents('general.json');
$json = json_decode($str,true);
$filename = "source.html";
$html = file_get_html($filename);
class matches {
var $day;
var $kickofftime;
var $result;
function matches ($day, $kickofftime, $tip){
$this->day=$day;
$this->kickofftime=$kickofftime;
$this->result=$result;
return $this;
}
}
$i=0;
$day=$html->find('h1',0);
$day->plaintext;
$day=str_replace("<h1>TODAY FOOTBALL FIXTURES: ","", $day);
$day=str_replace("</h1>","", $day);
$matchday = str_replace(array('MONDAY ', 'TUESDAY ', 'WEDNESDAY ', 'THURSDAY ', 'FRIDAY ', 'SATURDAY ', 'SUNDAY '), '', $day);
$matchday=str_replace(" ","-", $matchday);
$matchday=date('Y-m-d', strtotime($matchday));
foreach($html->find('table.fixtures') as $matches)
{
foreach ($matches->find('tr[class=a1],tr[class=a2]') as $matchesTR) {
$kickofftime=$matchesTR->find('td[class=a11],td[class=a21]',0)->plaintext;
$kodate = date('Y-m-d H:i:s', strtotime("$matchday $kickofftime +1 hour"));
$result=$matchesTR->find('td');
echo $kodate;
echo $result[6]->plaintext.'<br>' ;
$i++;
}
}
//Here is the 2nd foreach with the data of JSON source:
foreach($json as $key => $value) {
$value = json_decode($value, true);
echo $value["country"] . ", " . $value["competition"] . " " . $value["club"] . "<br>";
}
// clean up memory
$html->clear();
unset($html);
?>
The current results from the simple html dom html source:
2014-12-23 20:00:00 2-1
2014-12-23 11:00:00 3-1
2014-12-26 08:00:00 1-1
The result from the JSON source:
America Copa America Boca Juniors
Europe Bundesliga Hannover
Asia JLeague Nagoya
I would like to combine these two results in one foreach and I would like to get this result:
2014-12-23 20:00:00 2-1 America Copa America Boca Juniors
2014-12-23 11:00:00 3-1 Europe Bundesliga Hannover
2014-12-26 08:00:00 1-1 Asia JLeague Nagoya
I hope that there is some expert who can help for me because I tried a lot of variation but without result. I got some advice (with code) from experts, but there was everytime errors. With my code there is no error, but I need other solution because I would like to put all variables to one foreach. Many thanks, I hope that somebody could help me with code, because I am not on high level at php. Thanks again!
I would like to put the two foreach into one foreach, but I don't want to create a new array because I not need.
Assuming you will always have the same amount of items in each and that they match 1 to 1, 2 to 2, you can do this:
$htmlDates = array();
$jsonLeag = array();
foreach($html->find('table.fixtures') as $matches) {
foreach($matches->find('tr[class=a1],tr[class=a2]') as $matchesTR) {
$kickofftime=$matchesTR->find('td[class=a11],td[class=a21]',0)->plaintext;
$kodate = date('Y-m-d H:i:s', strtotime("$matchday $kickofftime +1 hour"));
$result=$matchesTR->find('td');
//echo $kodate;
//echo $result[6]->plaintext.'<br>' ;
$htmlDates[] = $kodates;
}
}
//Here is the 2nd foreach with the data of JSON source:
foreach($json as $key => $value) {
$value = json_decode($value, true);
//echo $value["country"] . ", " . $value["competition"] . " " . $value["club"] . "<br>";
$jsonLeag[] = $value["country"] . ", " . $value["competition"] . " " . $value["club"];
}
if(count($htmlDates) < count($jsonLeag)){
for($i=0;$i<count($htmlData);$i++){
echo $htmlData[$i] . " " . $jsonLeag[$i] . "<br />\r\n";
}
} else {
for($i=0;$i<count($jsonLeag);$i++){
echo $htmlData[$i] . " " . $jsonLeag[$i] . "<br />\r\n";
}
}
Since you have the nested list first and nothing ties the two data sets together, there is no simple way to run one loop and get the data from both. It's easier to push the data you want into an array for each set, and then walk both arrays with one counter. The caveat here is that if one has an extra element, you will get missing results or errors.
Save keys of json arrays and use the next in each loop.
$json_keys = array_keys($json);
$i_key = 0;
foreach($html->find('table.fixtures') as $matches)
{
foreach ($matches->find('tr[class=a1],tr[class=a2]') as $matchesTR) {
$kickofftime=$matchesTR->find('td[class=a11],td[class=a21]',0)->plaintext;
$kodate = date('Y-m-d H:i:s', strtotime("$matchday $kickofftime +1 hour"));
$result=$matchesTR->find('td');
echo $kodate;
echo $result[6]->plaintext.
$value = json_decode($json[$json_keys[$i_key++]], true);
echo $value["country"] . ", " . $value["competition"] . " " . $value["club"] . "<br>";
$i++;
}
}
// clean up memory
$html->clear();
unset($html);
There are many other variants - use array_shift(), next()... I've written the first come in mind
I am using a random PHP array for a raffle type script and I sometimes get the same string 3 or more times. How can I limit the random to only show a max of 2 of the same string?
For example I have:
<?php
$raffle = array('string1', 'string2', 'string3', 'string4', 'string5', 'string6');
echo $raffle[array_rand($raffle)] . ", " . $raffle[array_rand($raffle)] . ", " . $raffle[array_rand($raffle)] . ", " . $raffle[array_rand($raffle)];
?>
So it chooses a random of 4 strings from the array, but I don't want the same string to show up more than twice. How can I achieve this?
Below is a function that will store what has been pick, and if picked again, remove it from the array. Once removed from the array, it'll never get picked again. So items can show up twice, but not more:
function pull_raffle() {
static $raffle = array('string1', 'string2', 'string3', 'string4', 'string5', 'string6');
static $pulled_before = array();
$pick = array_rand($raffle);
$string = $raffle[$pick];
if (array_key_exists($string, $pulled_before)) {
unset($raffle[$pick]);
} else {
$pulled_before[$string] = true;
}
return $string;
}
Use it like this:
echo pull_raffle() . ", " . pull_raffle(). ", " . pull_raffle() . ", " . pull_raffle();
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