在forach循环中的php for循环,不知道如何做到这一点

时间:2015-03-06 14:31:34

标签: php for-loop foreach

我正在尝试在foreach循环中执行for循环。

我的数据库中有一个表格如下:

ID        | Fname | Lname
------------------------
1          Bart    Simpson
1          Mickey  Mouse
2          Peter   Griffin
2          Clark   Kenet
2          David   Johnson

我从数据库调用数据(并且它可以工作,在phpmyadmin上测试),我希望数据在页面上显示ID值例如:

巴顿辛普森,米老鼠&彼得格里芬

Clark Kenet&大卫约翰逊

正如你在“&”中看到的那样在任何一行的姓氏之前,但这不是我的问题。

这是我写的代码:

//HERE I RETRIVE ALL THE DATA FROM THE DATABASE.
$query = $dbh->query(" SELECT *
        FROM table
        WHERE ID= '{$ID}'
        ");   

//THIS CODE SHOWS THE NUMBER OF ROWS WITH THE CURRENT ID 
        $sql    = "SELECT COUNT( * ) FROM table WHERE ID= '{$ID}'";
        $result = $dbh->prepare($sql);
        $result->execute();
        $number_of_rows = $result->fetchColumn();

//THIS IS THE FOREACH IN WHICH I CALL ALL THE ROWS BY THEIR VALUE
          foreach ($query as  $key =>$value) {
                   $value['wFname'][$key] = !empty($value['wFname'][$key]) ? $value['wFname'][$key] : '';                      
$numRow = $number_of_rows-2; // THE ITEM BEFORE THE LAST ONE IN THE ARRAY
$lastItem = $number_of_rows-1; //LAST INDEX IN THE ARRAY
for($counter = 0; $counter = $numRow; $counter++){
 return  $value['wLname'][$counter] . ', '.  $value['wFname'][$counter];
  }
   return  "&" . $value['wLname'][$lastItem] . ', '.$value['wFname'][$lastItem] ;
   return ' ';

                };

使用此代码我只获得每个id的第一对名称。 任何帮助都会很棒。

1 个答案:

答案 0 :(得分:1)

尝试更改:

for($counter = 0; $counter = $numRow; $counter++){

到:

for($counter = 0; $counter =< $numRow; $counter++){

你正在检查$ counter是否等于$ numRow,你应该检查它是否等于且小于......

希望这有帮助。

编辑基于用户请求

尝试将结果存储在变量中并在两个循环结束时返回该变量,但我不确定您要在此处尝试实现的目标,请尝试运行以下代码:

//HERE I RETRIVE ALL THE DATA FROM THE DATABASE.
        $query = $dbh->query(" SELECT *
        FROM table
        WHERE ID= '{$ID}'
        ");

//THIS CODE SHOWS THE NUMBER OF ROWS WITH THE CURRENT ID 
        $sql = "SELECT COUNT( * ) FROM table WHERE ID= '{$ID}'";
        $result = $dbh->prepare($sql);
        $result->execute();
        $number_of_rows = $result->fetchColumn();

//THIS IS THE FOREACH IN WHICH I CALL ALL THE ROWS BY THEIR VALUE
        $return = "";
        foreach ($query as $key => $value) {
            $value['wFname'][$key] = !empty($value['wFname'][$key]) ? $value['wFname'][$key] : '';
            $numRow = $number_of_rows - 2; // THE ITEM BEFORE THE LAST ONE IN THE ARRAY
            $lastItem = $number_of_rows - 1; //LAST INDEX IN THE ARRAY
            for ($counter = 0; $counter <= $numRow; $counter++) {
                $return .= $value['wLname'][$counter] . ', ' . $value['wFname'][$counter];
            }
            $return .= "&" . $value['wLname'][$lastItem] . ', ' . $value['wFname'][$lastItem];
            $return .= ' ';
        }
        return $return;