So I have the following code with works great for randomly generating position for 5 different sidebar ads, my problem is how to give the ads a link that will always be paired with them.
I'm looking for suggestions from some PHP gurus as to best practices for doing this...
<ul class="top_ads">
<?php
$totalImages = 5;
$all = range(1,$totalImages);
shuffle($all);
foreach ($all as $single) {
echo "<li><a href='' /><img src='"; echo bloginfo('template_url') . "/images/ads/ad_0$single.png' alt='ad' /></li>";
}
?>
</ul>
The simplest way is to have an array of images with links and then have $single be the array index. There are two ways to accomplish this. One is to have a two dimensionsal array that contains both links and images, the other is to have two parallel arrays. Here are both options illustrated:
<?php
// one two dimensional array
$ads = array( array("1.png", "/page1"), array("2.png", "/page2"), array("3.png", "/page3"), array("4.png", "/page4"), array("super-special-buy-now.png", "/billy-mays-lives") );
// or two one dimensions arrays
$ads_images = array("1.png", "2.png", "3.png", "4.png", "super-special-buy-now.png");
$ads_links = array("/page1", "/page2", "/page3", "/page4", "/billy-mays-lives");
// now your code
$totalImages = 5;
$all = range(1,$totalImages);
shuffle($all);
$html = "";
foreach ($all as $single) {
// option 1, two dimensional array
$html += sprintf('<li><a href="%s"><img src="%s/images/ads/ad_0%s" alt="ad" /></li>',
$ads[$single][1], bloginfo('template_url'), $ads[$single][0]);
// option 2, two parallel arrays
$html += sprintf('<li><a href="%s"><img src="%s/images/ads/ad_0%s" alt="ad" /></li>',
$ads_links[$single], bloginfo('template_url'), $ads_images[$single]);
}
echo $html;
?>
Normally you would either:
- Shuffle them already in query which retrieves them from a database, or
- Shuffle an array of id/url pairs:
$d => array (
array('id'=>1,'url'=>'...'),
array('id'=>2,'url'=>'...')
array('id'=>3,'url'=>'...'));
array_shuffle($d);
Which would also make it easier to drop add 1 instead over overwriting it (with all server / browsercaching problems that could come from it).
Related
In essence, I have 3 arrays. These are serialised, stored to the DB, un-serialised and then outputted to a page. myFirstArray, mySecondArray, & myThirdArray.
From what I gather - I need to be using a foreach loop, or a for loop with a counter, as the 3 arrays are all of (the same) unknown length. By that I mean one user may have stored 4 items into each of the 3 arrays, but another user might have stored 8 items into each of the 3 arrays.
I'm trying to get the output to look something like this:
myFirstArray[0], mySecondArray[0], myThirdArray[0]
myFirstArray[1], mySecondArray[1], myThirdArray[1]
myFirstArray[2], mySecondArray[2], myThirdArray[2]
The current code I have is as follows:
foreach ($myFirstArray as $value1){
echo $value1 . " ";
}
foreach ($mySecondArray as $value2){
echo $value2 . " ";
}
foreach ($myThirdArray as $value3){
echo $value3 . "<br>";
}
I am aware that this code is never going to output my arrays as I would like, but I'm having some difficulty with working out the logic behind what I need. I haven't rushed straight to StackOverflow to ask, but nothing else I've seen has been very helpful!
Since both arrays have the same length, I propose
$length = count($myFirstArray);
for($i = 0; $i <$length ; $i++) {
echo $myFirstArray[$i].','.$mySecondArray[$i].','.$myThirdArray[$i].'<br/>';
}
This will loop through all of your arrays at the same time :) .
In PHP 5.5.33, I want to create an array of arrays, inside a repeat loop. I have found 3 different ways of doing this, which give 3 different results. The first result is the one I want, so I have a solution. What I need is an understanding of why these three ways lead to different outcomes.
The first two examples make sense to me. The third seems to apply alien logic. In the third example, I create a new reference to a new array on each iteration, and yet the same reference is added to the output array each time. Why does $inner, in the last example, not get recreated at a new memory address each time?
<?php
// Inner array added after it is changed
$outer = array();
for ($ii=0; $ii<3; $ii++) {
$inner = array("value" => 0);
$inner["value"] = $ii;
$outer[$ii] = $inner;
}
echo json_encode($outer);
// [{"value":0},{"value":1},{"value":2}]
?>
<br />
<?php
// Innner array added as a copy, and then changed
$outer = array();
for ($ii=0; $ii<3; $ii++) {
$inner = array("value" => 0);
$outer[$ii] = $inner;
$inner["value"] = $ii;
}
echo json_encode($outer);
// [{"value":0},{"value":0},{"value":0}]
?>
<br />
<?php
// Inner array created, then added by reference, then changed
$outer = array();
for ($ii=0; $ii<3; $ii++) {
$inner = array("value" => 0); // shouldn't this be different each time?
$outer[$ii] = &$inner;
$inner["value"] = $ii;
}
echo json_encode($outer);
// [{"value":2},{"value":2},{"value":2}]
?>
It is simple - on the 3th sample you're creating the array of 3 synonyms to the variable $inner['value']. In same tame you every time change the $inner['value'] to $ii. On the end you have array of 3 pointers, which point to $inner['value'], but $inner['value'] obtained 2 - that is and the result.
And in case you are expecting that $inner = array("value" => 0); will take different place - you aren't on right way. This is equal if you empty and create the array - it is reseting the array every time.
According to http://assemblysys.com/php-point-in-polygon-algorithm/ I can take a group of points that form a polygon and determine whether or not a point resides inside or outside the polygon. I have also created an KML file when is being utilized by JavaScript to determine which points are inside, however my end goal would to have each marker contain an extra data set inside of a MySQL table that will store this data for later use resulting in a quicker map load time.
Looking through the KML file, each Polygon has a set of coordinates that are separated by ",0.0" which means little because according to the above document I only need the set of lats and longs. In addition, the latitudes and longitudes are in different places. Below is an example of the cordinates:
-86.1459875,39.8622513,0.0 -86.1459875,39.8555639,0.0 -86.1398077,39.8556628,0.0 -86.1398077,39.862218399999996,0.0 -86.1459875,39.8622513,0.0
Instead I want the set to look like the following:
39.8622513 -86.1459875, 39.8555639 -86.1459875, 39.8556628 -86.1398077, 39.862218399999996 -86.1398077, 39.8622513 -86.1459875
Below is a sample of my code, however I am not sure if there is an easier way of manipulating the array using PHP without the use of multiple for loops or foreach loops.
$kml = 'document.xml';
//get the total number polygons
$numPoly = count( $kml->Document[0]->Folder);
$newArray = array();
$a = 1;
$explode;
$explode['coordinates'];
for( $i=0; $i <= $numPoly; $i++)
{
$numPlace = count( $kml->Document[0]->Folder[$i]->Placemark); //count the number of placemarks there are
for($z = 0; $z <= $numPlace; $z++)
{
$regionName = $kml->Document[0]->Folder[$i]->Placemark[$z]->name."</br>"; //grab each placemarks name
//get the cordinates inside of each placemark
$regionCords = $kml->Document[0]->Folder[$i]->Placemark[$z]->Polygon->outerBoundaryIs->LinearRing->coordinates;
//print_r($regionCords); print "<br/><br/>";
foreach($regionCords as $num2 => $region)
{
print $a;
$explodeCords = array_splice( explode('|', str_replace(',0.0',' |', $regionCords) ), 0, -1 ) ;
foreach ($explodeCords as $exploded)
{
$exploded = explode(',', $exploded);
$exploded1 = $exploded[0];
$exploded2 = $exploded[1];
$explodedString = $exploded2.$exploded1.",";
//echo $explodedString; echo "<br/><br/>";
}
}
$numCordinates = count($explodeCords['coordinates'] ); //returns the number of [lat,long] cords in each cordinate set
if ( !empty( $regionCords ) )
{
$a++;
}
}
}
Please let me know if I am on the right path or if there is another way you can easily switch these two numbers using mostly array functions with PHP.
A solution: after each foreach loop, it is best practice to remove the new array out of the loop, because if you are to add another foreach loop, unwanted effects may result such as appending a value to a new array in multiples.
After the values are removed from the foreach loop, you can always use a array_map to switch the coordinates. For a more completed example of this please see the following Github repo: https://github.com/jdmagic21/GMapParse
I have an array which contains sets of three similar named items; however, sometimes there's only two items in a set and I want to call these out.
<?php
$items = array(
'reviewpitfighter-1.138x88.jpg',
'reviewpitfighter-2.138x88.jpg',
'reviewpopfulmailsegacd-1.138x92.jpg',
'reviewpopfulmailsegacd-2.138x76.jpg',
'reviewpopfulmailsegacd-3.138x97.jpg'
);
?>
You'll note that there are two reviewpitfigher* items, and three reviewpopfulmailsegacd* items. I've started down a rabbit hole of loops and feel that there is something simple I'm just glossing over.
May be you can do this as a 2 stage process.
Stage 1:
Loop through the original array and form another set of array with its key as the value of this original array. Then save the repetition count in each of those new arrays.
Stage 2:
Loop through the new set of arrays and then pick out the arrays which has values less than 3 and retrieve its key.
Hope this helps!!
Here's the solution I came up with, sorry it took so long to post.
foreach($images as $value){
$lastItem = explode('-', $images[$count - 1]);
$parts = explode('-', $value);
if(preg_match('/^1/', $parts[1]) && $count != 0){
if(preg_match('/^2/',$lastItem[1])){
$imgurl = preg_replace('/^p?review/','',$lastItem[0]);
$sql = 'SELECT field FROM table WHERE field = "' . $imgurl . '"';
$result = $dbConn->FetchArray($dbConn->Query($sql), MYSQL_ASSOC);
$array[$imgurl] = $result;
}
}
$count++;
}
I get an array of all the images, then I check to see if I'm looking at the first image, if I am then I see if the last image I looked at was the second image. At this point I then call into the database to get some information to display a neatly messaged out put of what reviews are missing a third image. In the end $array contains this list which I can loop over.
I have been trying to get this to work for a while now!
What I am trying to do is sort two arrays, so they both get ordered depending on the values inside one of the arrays. I don't know how to "attach" the arrays so both get ordered.
Here is my code:
$html = file_get_html('http://www.amazon.co.uk/s/ref=nb_sb_noss?url=search-alias%3Daps&field-keywords=hat&x=0&y=0');
$test = strtolower("Beechfield Turn-up Beanie");
$arrayT = array();
$arrayP = array();
foreach ($html->find('div.product') as $results) {
foreach ($results->find('a.title') as $title) {
$titleLow = strtolower($title->plaintext);
similar_text($test, $titleLow, $percent);
$arrayT[] = $title->plaintext;
$arrayP[] = round($percent);
}
}
I am comparing how similar the titles brought back from the outside website are to the variable $test, which in this case is just an example.
Next I want my output to be sorted depending on the $percent variables. For example with no sorting the output would be:
title-1 55
title-2 90
title-3 66
However I want it to be sorted:
title-2 90
title-3 66
title-1 55
I have tried using array_multisort however it would only sort each array independently. I have had a look at usort and ksort as well but couldn't get a working answer.
Any help would be appreciated! I have never used any kind of sorting in PHP and have only started learning arrays so please go easy on me.
I would suggest you to do this:
Instead of storing title and percentage in two different array.
you can have array indices as the titles.
Like this:
$html = file_get_html('http://www.amazon.co.uk/s/ref=nb_sb_noss?url=search-alias%3Daps&field-keywords=hat&x=0&y=0');
$test = strtolower("Beechfield Turn-up Beanie");
$arrayTP = array();
foreach ($html->find('div.product') as $results) {
foreach ($results->find('a.title') as $title) {
$titleLow = strtolower($title->plaintext);
similar_text($one, $titleLow, $percent);
$arrayTP[$title->plaintext] = round($percent);
}
}
You can sort it later using an array sort function based on the percentage. Use this: asort.
Because:
This function sorts an array such that array indices maintain their correlation with the array elements they are associated with. This is used mainly when sorting associative arrays where the actual element order is significant.
For printing do this:
foreach($arrayTP as $title => $percent ) {
.
.
.