reubenCanowski
reubenCanowski

Reputation: 262

PHP compare current array value to previous value

I've got an array with images and a date for each one. I'm retrieving the date via array explode. I want to take this date value and compare it to the previous date value for the previous image. My goal here is to display these dates as headers for the sets of images that correspond to each different date.

Here is my code I've been fiddling with to try and make this work (sorry for all my slashes):

$p = 0;
$a = -1;
echo "<table>";
echo "<tr>";
foreach (array_combine($images,$locs) as $image => $loc)
{
    $p++;
    $a++;
    $datesort = explode('>',$image);
    echo "<style>";
    echo "input[label=t" . $p . "]    {";
    echo "display: none;";
    echo "}";
    echo "input[label=t" . $p . "] + label   {";
    echo "border: 5px solid #FFFFFF;";
    $image = "background: url('http://blah.com/" . $loctb[$p] . "');";
    echo $image;
    echo "height: 61px;";
    echo "width: 92px;";
    echo "display: inline-block;";
    echo "padding: 0 0 0 0px;";
    echo "}";
    echo "input[label=t" . $p . "]:checked + label   {";
    echo "border: 5px solid #FF9900;";
    echo "background: url('http://blah.com/" . $loctb[$p] . "');";
    echo "height: 61px;";
    echo "width: 92px;";
    echo "display: inline-block;";
    echo "padding: 0 0 0 0px;";
    echo "}";
    echo "</style>";
    $lastdate = array("");
    $lastdate[$a] = $datesort[1];
    echo "<td>";
    if ($lastdate[$a] <> $datesort[1]){
    echo "<h2>";
    echo $datesort[1];
    echo "</h2>";
    }
    echo "<input type=\"checkbox\" label=\"t" . $p . "\" id=\"t" . $p . "\" name =\"boxes[]\" value=\"<img src=http://blah.com/" . $loc . "\" />";
    echo "<label for=\"t" . $p . "\"></label>";
    echo "</div>";
    echo "</td>";
    if ($p % 2 == 0)
    {
    echo "</tr>";
    }
}
echo "</table>";

I've been trying to store the current date value into another array variable and then compare that to the new value the next time through my foreach loop, but I'm doing it wrong :-/...

I'd appreciate any help you can offer. Thanks

Upvotes: 4

Views: 2497

Answers (1)

Anthony
Anthony

Reputation: 37065

Here is a quick and dirty way, though you'll want to tune it to your needs (I had this issue but it was worse as I was also filling in the blank dates in between):

$previous_dates = array();

foreach (array_combine($images,$locs) as $image => $loc) {

    $datesort = explode('>',$image);

    if (end($previous_dates) <> $datesort[1]) {
       echo "<h2>";
       echo $datesort[1];
       echo "</h2>";
    }
      // ... more stuff ...//

    $previous_dates[] =  $datesort[1];
}

Really I would reconsider the approach you're taking for the explode within the loop, but first-things-first, see if that gets you where you need to be.

Upvotes: 2

Related Questions