views:

88

answers:

4

Hi everyone!

Is it possible to save loop results to a string?

$sql = "SELECT SUBSTR(a.`title`, 1,1) FROM articles a WHERE a.`tag` = 'human_resources'";
$results = db_query($sql);
  while ($fields = db_fetch_array($results)) {
     foreach($fields as $key => $value) {
       echo $value;
     }
  }

The code above outputs titles of articles with a tag human_resources. I want to make an alphabar for a catalog, so I'm using this:

if(stripos($string, "A") !== false) {
    echo ('<a href="http://www.mysite.com/articles/A"&gt;A&lt;/a&gt;');
}
else echo '<span class="inactive">A</span>';

if(stripos($string, "B") !== false) {
    echo ('<a href="http://www.mysite.com/articles/B"&gt;B&lt;/a&gt;');
}
else echo '<span class="inactive">B</span>';

...etc

But I don't know how to get that $string from the loop for the second part of code.

Any suggestions or better approach to this problem are greatly appreciated.

A: 

I'm not sure exactly what you want... update your examples to show what you have and what you want the result to be.

You can store a list of values using an array:

$list = array();
for (...) {
    /*
    Some code here...
    */
    // Add the current string to the list.
    $list[] = $string;
}

If you just want one long string, you can append:

$all = "";
for (...) {
    /*
    Some code here...
    */
    // Add the current string to a string with all the strings concatenated.
    $all .= $string;
}
Blixt
A: 

Change this:

echo $value;

to this:

$string .= $value;
palindrom
A: 
while ($fields = db_fetch_array($results)) {
     foreach($fields as $key => $value) {
      echo $value;
     }
}

try

$result = "";
while ($fields = db_fetch_array($results)) {
     foreach($fields as $key => $value) {
      $result = $result . $value;
     }
}
restun $result
schubySteve
A: 

In addition to what everybody else has said, you will likely want to use a loop to display your alphabetical menu:

for ($i = 65; $i < 91; $i++) {
     $letter = chr($i);
     if(stripos($string, $letter) !== false) {
          echo ('<a href="http://www.mysite.com/articles/'.$letter.'"&gt;'.$letter.'&lt;/a&gt;');
     }
     else echo '<span class="inactive">'.$letter.'</span>';
}

This will save you having to copy and paste the code for each letter.

sixfoottallrabbit