I'm pulling 5 random rows from a csv file such as an image, year, hint text and caption text:
<?php
$rows = file('Book1.csv');
$len = count($rows);
$rand = array();
while (count($rand) < 5) {
$r = rand(0, $len);
if (!in_array($r, $rand)) {
$rand[] = $r;
}
}
echo 'var cardDeck = [';
foreach ($rand as $r) {
$csv = $rows[$r];
$data = str_getcsv($csv);
echo "{\n";
echo "'image':'".$data[1]."',\n";
echo "'year':'".$data[0]."',\n";
echo "'hint':'".$data[3]."',\n";
echo "'caption':'".$data[2]."'";
echo "\n},\n";
}
?>
My output which is correct and how I want it:
var cardDeck = [{
'image':'<img class="img_card" src="https://www.floridamemory.com/onlineclassroom/game/cards/1898.png">',
'year':'1898',
'hint':'Tampa during the Spanish American War',
'caption':'1898-Early in 1898, President William McKinley sent the battleship Maine to Havana to protect American interests. The war lasted only until August, when the two belligerents signed an armistice. A final treaty was signed in December 1898. Read More'
},
{
'image':'<img class="img_card" src="https://www.floridamemory.com/onlineclassroom/game/cards/1845.png">',
'year':'1845',
'hint':'Act establishing Florida statehood',
'caption':'1845-The Act establishing statehood for Iowa and Florida was approved on March 3, 1845 by the second session of the 28th Congress. Read More'
},
{
'image':'<img class="img_card" src="https://www.floridamemory.com/onlineclassroom/game/cards/1822.png">',
'year':'1822',
'hint':'Territory of Florida Established',
'caption':'1822-This first act of Florida\'s Territorial Legislature in 1822 divided the territory into four counties and established local courts. Read More'
},
{
'image':'<img class="img_card" src="https://www.floridamemory.com/onlineclassroom/game/cards/1904.png">',
'year':'1904',
'hint':'Mary McLeod Bethune opens her school',
'caption':'1904-Mary McLeod Bethune founded the Daytona Normal and Industrial School for Negro Girls. Her school later merged with the Cookman Institute of Jacksonville in 1923 and today is known as Bethune-Cookman University. Read More'
},
{
'image':'<img class="img_card" src="https://www.floridamemory.com/onlineclassroom/game/cards/1912.png">',
'year':'1912',
'hint':'First train in Key West',
'caption':'1912-January 22, 1912 the first passenger train arrived in Key West, marking the completion of Henry Flagler\'s East Coast Railroad from Jacksonville to the Southernmost City. <a hre="https://www.floridamemory.com/blog/2013/01/22/first-train-to-key-west-january-22-1912/">Read More</a>'
},
];
But I was wondering if it was possible to list each year $data[0] and echo them individually for future use elsewhere? Like explode it or something?
Like:
<ul>
<li>1898</li>
<li>1845</li>
<li>1822</li>
<li>1904</li>
<li>1912</li>
</ul>
just walk through the array
$years = [];
foreach ($rand as $r) {
$csv = $rows[$r];
$data = str_getcsv($csv);
if (!in_array($data[0], $years)) {
$years[] = $data[0];
}
}
Related
I'm doing this for school, but am currently stuck with trying to get the array to echo the car in the budget range, but i cant figure out how to do it
so what ive tried doing so far is;
if ((isset($_POST["one"])) && (!empty($_POST["one"]))) {
$hi = $_POST["one"];
$arrayName = array('2018 Ford Mustang', '2019 Honda Civic Sedan VTi-L', 'Mazda RX-7', '2018 Honda NSX', 'Jeep Cherokee', 'Jeep Grand Cherokee', '2018 Ford Focus', '2018 Ford Fiesta', 'Nissan patrol ST');
$arrayprice = array('40000', '31795', '50000', '380000', '44000', '54990', '34490', '20525', '19990');
foreach ($arrayprice as $key => $value)
{
switch ($arrayprice)
{
case $hi >= $value: echo "<p>".$arrayName[$key]."</p>"; break;
case $hi <= '20000' && $hi >= '30000': echo $arrayName["0"];
and the same thing, but instead of the zero i had [$key] '0'
if ((isset($_POST["one"])) && (!empty($_POST["one"]))) {
$hi = $_POST["one"];
$arrayName = array('2018 Ford Mustang', '2019 Honda Civic Sedan VTi-L', 'Mazda RX-7', '2018 Honda NSX', 'Jeep Cherokee', 'Jeep Grand Cherokee', '2018 Ford Focus', '2018 Ford Fiesta', 'Nissan patrol ST');
$arrayprice = array('40000', '31795', '50000', '380000', '44000', '54990', '34490', '20525', '19990');
foreach ($arrayprice as $key => $value)
{
switch ($arrayprice)
{
case $hi >= $value: echo "<p>".$arrayName[$key]."</p>"; break;
case $hi <= '20000' && $hi >= '30000': echo $arrayName[$key]'0';
i want it to output the array index that I put in as the car in that budget range. for example if the budget range is between 20000 and 30000 then it should output the ford fiesta, whereas, if the budget is between 10000 and 20000 it should output the nissan patrol st.
(I'm new to programming and all that and just asking for a friend, sorry if you can't understand what I'm trying to say or explain)
Use database and make a table with column names containing this data.
car_model_name,
price
you can easily manage those things that you want to make.
Then connect to your table and display the list of all car models
then create a condition or statement that will check if the price is in between the $hi price.
It was hard to fix your problem because you don't have any identifier connected to the car_model_name.
if (!empty($_POST["one"])) {
$hi = $_POST["one"];
$arrayName = array('2018 Ford Mustang', '2019 Honda Civic Sedan VTi-L', 'Mazda RX-7', '2018 Honda NSX', 'Jeep Cherokee', 'Jeep Grand Cherokee', '2018 Ford Focus', '2018 Ford Fiesta', 'Nissan patrol ST');
$arrayprice = array('40000', '31795', '50000', '380000', '44000', '54990', '34490', '20525', '19990');
$cars_that_fits = []; // every car you can get for your money
$max_fit = 0; // best car for your money
$max_fit_name = '';
foreach ($arrayprice as $key => $value) {
if ($value < $hi) {
$cars_that_fits[] = $arrayName[$key];
if ($max_fit < $hi) { $max_fit = $hi; $max_fit_name = $arrayName[$key]; }
}
}
}
I'm trying to manage some files on my personal web server that I use for XBMC but all the files (Movies from YIFY) have names like
Jumanji.1995-720p.YIFY.mp4
Silver.Linings.Playbook.2012.1080p.x264.YIFY.mp4
American Hustle (2013) 1080p BrRip x264 - YIFY.mp4
Notice that some of the items are separated with . and others with _ or spaces.
So what I need to do is to preg_match the file to an array of (title,year,quality) I only know some preg_match basics.
But this is way to hard for me.
e.g
echo extract('American Hustle (2013) 1080p BrRip x264 - YIFY.mp4');
This should output =
array(
'title' => 'American Hustle',
'year' => '2013',
'quality' => 1080p
);
Thanks in advance
^(.*?)\W+(\d{4})(?=[\W ]+?(\d{3,4})p)
You can try this.See demo.
https://regex101.com/r/nS2lT4/29
The regex starts and captures anything from start to a non word letter which can be one or more and has 4 digits ahead of it.After this a lookahead makes sure that after capturing \d{4} there are non word letters which can be one or more and has 4 digits of p ahead of it.Because of lookahead we capture the last 4 digits which have only non word characters and 4 digits p after them.
you have 3 differents formats then you need 3 differents parsing types
try this :
$tests = array(
// format 1
"Jumanji.1995-720p.YIFY.mp4",
"Silver.Linings.Playbook.2012-1080p.YIFY.mp4",
"American.Hustle.2013-1080p.YIFY.mp4",
// format 2
"Jumanji.1995.720p.x264.YIFY.mp4",
"Silver.Linings.Playbook.2012.1080p.x264.YIFY.mp4",
"American.Hustle.2013.1080p.x264.YIFY.mp4",
// format 3
"Jumanji (1995) 720p BrRip x264 - YIFY.mp4",
"Silver Linings Playbook (2012) 1080p BrRip x264 - YIFY.mp4",
"American Hustle (2013) 1080p BrRip x264 - YIFY.mp4",
);
function extractInfos($s) {
$infos = array();
if (FALSE === strpos($s, ".YIFY.")) {
// format 3
$tab = explode(" ", $s);
$yearIndex = count($tab) - 6;
$infos["year"] = trim($tab[$yearIndex], "()");
$infos["quality"] = $tab[$yearIndex + 1];
array_splice($tab, $yearIndex);
$infos["title"] = implode(" ", $tab);
} else {
// format 1 or 2
$tab = explode(".", $s);
$yearIndex = count($tab) - 3;
if (FALSE === strpos($tab[$yearIndex], "-")) {
// format 2
$yearIndex -= 2;
$infos["year"] = $tab[$yearIndex];
$infos["quality"] = $tab[$yearIndex + 1];
} else {
// format 1
list($infos["year"], $infos["quality"]) = explode("-", $tab[$yearIndex]);
}
array_splice($tab, $yearIndex);
$infos["title"] = implode(" ", $tab);
}
return $infos;
}
echo "<table border=\"1\">";
foreach ($tests as $s) {
$infos = extractInfos($s);
?>
<tr>
<td>
<?php echo $infos["title"];?>
</td>
<td>
<?php echo $infos["year"];?>
</td>
<td>
<?php echo $infos["quality"];?>
</td>
</tr>
<?php
}
echo "</table>";
I'm trying to make this works. I want to replace some parts of a sentence between given positions and then show the full sentence with the changes. With the following code, I'm able to make the changes but I don't know how to put together the rest of the sentence.
I have two arrays, one with the positions where a woman name appears and another one with men names. The code replaces the pronoun "his" by "her" when a woman is before a man between the intervals. The last thing I need is to reconstruct the sentence with the changes made but I don't know how to extract the rest of the sentence (the result, in the example, is from positions 0 to 20 (Maria her dress but) and 36 to 51 (Lorena her dog) but I need to extract from 20 to 36 (Peter his jeans) and 51 to the end (Juan his car) to merge them in their positions).
The result should be: "Maria her dress but Peter his jeans Lorena her dog Juan his car". I'll appreciate any help with this, I've been looking for other similar questions but I found nothing.
<?php
$womenpos = array("0","36"); //these arrays are just examples of positions
$menpos = array("20","51"); //they will change depending on the sentence
$sentence = "Maria his dress but Peter his jeans Lorena his dog Juan his car";
echo $sentence."\n";
foreach ($womenpos as $index => $value) {
$value2 = $menpos[$index];
if($value < $value2) {
echo "\nWoman(" . $value . ") is before man(" . $value2 . ")\n";
$end = ($value2 - $value);
$improved = str_replace(' his ', ' her ',
substr($sentence, $value, $end));
echo $improved."\n";
} else {
$improved = "Nothing changed";
echo $improved;
}
}
Ok, how about this:
$womenpos = array("0","36");
$menpos = array("20","51");
$bothpos = array_merge($womenpos,$menpos);
sort ($bothpos);
print_r($bothpos);
$sentence = "Maria his dress but Peter his jeans Lorena his dog Juan his car";
echo $sentence."\n";
for ($i = 0; $i<sizeof($bothpos); $i++) {
$start = $bothpos[$i];
if ($i ==sizeof($bothpos)-1) {
$end = strlen($sentence);
}
else {
$end = $bothpos[$i+1];
}
$length = $end-$start;
$segment = substr($sentence, $start, $length);
if (in_array($start, $womenpos)) {
$new_segment = str_replace (' his ', ' her ', $segment);
}
else { $new_segment = $segment; }
$improved .= $new_segment;
print "<li>$start-$end: $segment : $new_segment </li>\n";
}
print "<p>Improved: $improved</p>";
This combines the men's and women's position arrays to consider each stretch of text as one that might have an error. If that stretch of text starts at one of the womenpos points, then it changes 'his' to 'her'. If not it leaves it alone.
Does this get you in the direction you want to go in? I hope so!
This approaches the problem differently, but I wonder if it would provide the solution you're looking for:
$sentence = "Maria his dress but Peter his jeans Lorena his dog Juan his car";
$women = array ("Maria", "Lorena");
$words = explode (" ", $sentence);
for ($i=0; $i< sizeof($words); $i++) {
if ($words[$i] == "his" && in_array($words[$i-1], $women)) {
$words[$i] = "her";
}
}
print (join(" ", $words));
This goes through the words one at a time; if the preceding word is in the $women array and the current word is "his", it changes the word to "her". Then it spits out all the words in order.
Does this do what you need, or do you really want a complex string positioning answer?
OK here is what i want to do
I have an array that contains keywords
$keywords = array('sport','messi','ronaldo','Barcelona','madrid','club','final','cup','player');
and i have another array that contains my whole titles
let's say
$titles = array('Real Madrid is the only club to have kept a European cup by winning it five times in a row.','Cristiano Ronaldo is World Soccer's Player of the Year 2013.','Lionel Messi Reaches $50 Million-A-Year Deal With Barcelona','','');
so now what i want to do
is to loop my keywords array in each of the titles array element
and if there is 3 keywords in one element then do something
for example
$titiles[0] // this one has these words => Madrid , cup club
so this one is have at least 3 words of my keywords
so if each element has 3 keywords or more , then echo that array element.
any idea on how to get this working?
foreach ($titles as $t){
$te=explode(' ',$t);
$c=count(array_intersect($te,$keywords));
if($c >=3){
echo $t.' has 3 or more matches';
}
}
live demo: http://codepad.viper-7.com/7kUUEK
2 matches is your current max
if you want Madrid to match madrid
$keywords=array_map('strtolower', $keywords);
foreach ($titles as $t){
$te=explode(' ',$t);
$comp=array_map('strtolower', $te);
$c=count(array_intersect($comp,$keywords));
if($c >=3){
echo $t.' has 3 or more matches';
}
}
http://codepad.viper-7.com/itdegA
Alternatively, you could also use substr_count() to get the number of occurances. Consider this example:
$keywords = array('sport','messi','ronaldo','Barcelona','madrid','club','final','cup','player');
$titles = array('Real Madrid is the only club to have kept a European cup by winning it five times in a row.',"Cristiano Ronaldo is World Soccer's Player of the Year 2013.","Lionel Messi Reaches $50 Million-A-Year Deal With Barcelona",'','');
$count = 0;
$data = array();
foreach($titles as $key => $value) {
$value = strtolower($value);
$keys = array_map('strtolower', $keywords);
foreach($keys as $needle) {
$count+= substr_count($value, $needle);
}
echo "In title[$key], the number of occurences using keywords = " .$count . '<br/>';
$count = 0;
}
Sample Output:
In title[0], the number of occurences using keywords = 3
In title[1], the number of occurences using keywords = 2
In title[2], the number of occurences using keywords = 2
In title[3], the number of occurences using keywords = 0
In title[4], the number of occurences using keywords = 0
Fiddle
Simpler with array_intersect:
$keywords = array('sport','messi','ronaldo','Barcelona','madrid','club','final','cup','player');
$titles = array('Real Madrid is the only club to have kept a European cup by winning it five times in a row.','Cristiano Ronaldo is World Soccer\'s Player of the Year 2013.','Lionel Messi Reaches $50 Million-A-Year Deal With Barcelona');
foreach($titles as $title) {
if (count(array_intersect(explode(' ',strtolower($title)), $keywords)) >= 3) {
//stuff
}
}
I am doing a GET php function on a URL and I get back the resulting response in JSON:
{
"results": [{
"text": "The 2014 BICSI Canadian Conference and Exhibition in Vancouver, British Columbia, Canada is 61 days away on April 27 - 30.",
"createdAt": "2014-02- 24T19:54:08.707Z",
"updatedAt": "2014-02-24T19:54:08.707Z",
"objectId": "ZZrZ9OgyRG"
}, {
"text": "Only 33 more days fro the 2014 BICSI Canadian Conference and Exhibition in Vancouver, Canada!",
"createdAt": "2014-03-24T13:23:56.240Z",
"updatedAt": "2014-03-24T13:23:56.240Z",
"objectId": "ZqxJRiHoJo"
}]
}
I am able to do php json_decode and display the results below on a web page like below
text | The 2014 BICSI Canadian Conference and Exhibition in Vancouver, British Columbia, Canada is 61 days away on April 27 - 30.
createdAt | 2014-02-24T19:54:08.707Z
updatedAt | 2014-02-24T19:54:08.707Z
objectId | ZZrZ9OgyRG
text | Only 33 more days fro the 2014 BICSI Canadian Conference and Exhibition in Vancouver, Canada!
createdAt | 2014-03-24T13:23:56.240Z
updatedAt | 2014-03-24T13:23:56.240Z
objectId | ZqxJRiHoJo
The php code I used to display the results above on the web page is:
$returned_content = get_data('https://api.parse.com/1/classes/Alerts');
$data = json_decode($returned_content, true);
foreach ($data as $array1 => $arrayn) {
foreach ($arrayn as $k => $v) {
foreach ($v as $t => $s) {
echo"<p> $t | $s ";
}
}
}
If I just wanted to display the 'text' key/value info only on the web page, how should I modify the php. Meaning all I want to see displayed on the web page is:
text | The 2014 BICSI Canadian Conference and Exhibition in Vancouver, British Columbia, Canada is 61 days away on April 27 – 30.
text | Only 33 more days fro the 2014 BICSI Canadian Conference and Exhibition in Vancouver, Canada!
$data = json_decode($json);
foreach ($data->results as $item) {
echo '<br>text | '.$item->text;
}
If you don't add the second json_decode() paremeter, you can just use your JSON with the StdClass.
Wrap it inside a simple if condition.
foreach ($data as $array1 => $arrayn) {
foreach($arrayn as $k => $v) {
foreach ($v as $t => $s) {
if($t == 'text') {
echo"<p> $t | $s ";
}
}
}
}
do like this
$returned_content = get_data('https://api.parse.com/1/classes/Alerts');
$data = json_decode($returned_content, true);
foreach ($data as $array1 => $arrayn) {
foreach($arrayn as $k => $v){
foreach ($v as $t => $s)
{
if($t == "text")
echo"<p> $t | $s ";
}
}
}
After this line :
$data = json_decode($returned_content, true);
You have an associative array, so you can change your loop to :
foreach ($data as $array1 => $arrayn) {
foreach($arrayn as $k => $v) {
foreach ($v as $t => $s) {
if('text' === $t) {
echo"<p> $t | $s ";
}
}
}
}
Make it simple and with a check if the key exists, just in case the JSON does not contain the key "text" it will return notice.
$data = json_decode($str,true);
foreach($data["results"] as $key=>$val){
if(array_key_exists("text",$val)){
echo 'text | '.$val["text"];
echo '<br />';
}
}
Here $str is your json string.