Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
408 views
in Technique[技术] by (71.8m points)

PHP : how to use foreach loop inside an echo statement?

i am tring to put a loop to echo a number inside an echo ; and i tried as bellow :

     $array = array();
     $result = mysql_query("SHOW TABLES FROM `st_db_1`");
     while($row = mysql_fetch_row($result) ){
     $result_tb = mysql_query("SELECT id FROM $row[0] LIMIT 1");
     $row_tb=mysql_fetch_array($result_tb);
     $array[] = $row[0];
     $array2[] = $row_tb[0];
     //checking for availbility of result_tb
     /*   if (!$result_tb) {
                  echo "DB Error, could not list tablesn";
                  echo 'MySQL Error: ' . mysql_error();
                  exit;
                  }  */
     }
     natsort($array);
     natsort($array2);

    foreach ($array as $item[0]  ) {
    echo "<a href=show_cls_db.php?id= foreach ($array2 as $item2[0]){echo "$item2[0]"}>{$item[0]}<br/><a/>" ;
    }

but php is not considering foreach loop inside that echo ; please suggest me something

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

As mentioned by others, you cannot do loops inside a string. What you are trying to do can be achieved like this:

foreach ($array as $element) {
    echo "<a href='show_cls_db.php?id=" . implode('', $array2) . "'>{$element}</a><br/>";
}

implode(...) concatenates all values of the array, with a separator, which can be an empty string too.

Notes:

  1. I think you want <br /> outside of <a>...</a>
  2. I don't see why you would want to used $item[0] as a temporary storage for traverser array elements (hence renamed to $element)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...