views:

55

answers:

1

On my project there're various search results of different content-types. For unimportant reasons, not all content-types carry a unique ID. However, I tried to write this loop that will detect IDless content-types, and will give them a unique ID.

Basically, the results look like this:

  • Category ID 3
  • Category ID 3
  • Category ID 4
  • NON-ID Category 1
  • NON-ID Category 2

[...]

I tried this:

$current = $result->section;      
// if there's a category ID -- use it
if ($current != null) echo $result->sectionid;
 else
 // if this is the first IDless category -- initialize. this happens once.
 if ($virginity == true) {
  $store = $current;
  $virginity = false;        
  }
// if initialized and current category string is the same as stored category string -- print it
if (($virginity == 0) && ($store = $current)) {
 echo $defaultID;
 }
// if initialized and current category string is different from the stored category string -- set new default category +1 and print it
if (($virginity == false) && ($store != $current)) {
 $defaultID = $defaultID++;
 echo $defaultID;
 $store = $current;
 }

Can you see where I'm going here? Trying to give each new category that comes up in the search results a unique ID, on the next loop session - check if the category string is same as the previous one, if so -- use the same ID, else -- bump ID by 1, print the new ID and store a new category.

However: This doesn't work properly.

Why?

A: 

Your code is a little tough to read, but a big red flag I see is this block:

//You have  a single equals sign here v
if (($virginity == 0) && ($store = $current)) 
{
    echo $defaultID;
}

That means that as long as $virginity==0, that line will always be run, and $store will always equal $current.

By the way, I'm going to recommend some reformatting and readability suggestions. Take them or leave them , though, it's just my opinion.

$current = $result->section;

if ($current != null) {//if one of the results has brackets, put brackets on both echo $result->sectionid; } else if ($virginity == true) {// if this is the first IDless category -- initialize. this happens once. $store = $current; $virginity = false;
}

//you're setting $virginity=false or true, so doing !$virginity makes sense
// if it was actually a number, then comparing to 0 is better
// also, use parentheses only where really needed, otherwise it's just clutter
if (!$virginity && $store == $current) 
{
    echo $defaultID;
}

if (!$virginity && $store != $current) {// if initialized and current category string is different from the stored category string -- set new default category +1 and print it $defaultID = $defaultID++; echo $defaultID; $store = $current; }

notJim