简体   繁体   English

从foreach循环中的特定列获取价值

[英]Get Value From Specific Column In foreach Loop

I have a query and I loop through its results to display the records inside a table, and this is working fine. 我有一个查询,并遍历其查询结果以在表中显示记录,并且工作正常。

My table has 5 columns: RecID, Name, Feedback, Score, and Product. 我的表有5列:RecID,名称,反馈,分数和产品。

As you can see the loop below will list all 5 columns. 如您所见,下面的循环将列出所有5列。 What I would like to do is only list 4 of the columns: Name, Feedback, Score, and Product, but store the RecID into a variable called $RecID . 我只想做四列:名称,反馈,分数和产品,但是将RecID存储到名为$RecID的变量中。 Then I will use the $RecID in the Delete link to call the Ajax function to delete the record based on the ID. 然后,我将使用Delete链接中的$ RecID来调用Ajax函数以根据ID删除记录。

How can I exclude a specific column in the display and also capture the RecID value to store in a variable $RecID ? 如何在显示中排除特定列并捕获RecID值以存储在变量$RecID

<?php
    while($dataArray = mysql_fetch_array($queryexe, MYSQL_ASSOC))
    {
        echo "<tr>\n";
        foreach ($dataArray as $col_value) {

            echo "\t<td>$col_value</td>\n";
        }
        //echo "<td><a onclick('deleteRecord(" + $recID + ")'>Delete</a></td>";
        echo "</tr>\n";
    }
?>

Don't use a loop to show the columns, just access the fields you want directly using $dataArray['colname'] . 不要使用循环来显示列,只需直接使用$dataArray['colname']访问所需的字段即可。

<?php
while($dataArray = mysql_fetch_array($queryexe, MYSQL_ASSOC))
{
    echo "<tr>\n";
    echo "<td>{$dataArray['Name']}</td><td>{$dataArray['Feedback']}</td><td>{$dataArray['Score']}</td><td>{$dataArray['Product']}</td>";
    echo "<td><a onclick('deleteRecord({$dataArray['RecID']})'>Delete</a></td>";
    echo "</tr>\n";
}
?>

You can modify your foreach loop to get the column name as well as its value. 您可以修改foreach循环以获取列名及其值。 Then, inside the loop, you can check for the specific column name you want and process it differently than the others. 然后,在循环内部,您可以检查所需的特定列名称,并对其进行不同的处理。

while($dataArray = mysql_fetch_array($queryexe, MYSQL_ASSOC)) {
    echo "<tr>\n";
    foreach ($dataArray as $col_name => $col_value) {
        if ($col_name == 'RecID') {
            echo "<td><a onclick('deleteRecord(" . $col_value . ")'>Delete</a></td>";
        } else {
            echo "\t<td>$col_value</td>\n";
        }
    }
    echo "</tr>\n";
}

You can read about the differences between the two different syntaxes for foreach and how they should be used in the PHP documentation . 您可以了解foreach的两种不同语法之间的区别以及如何在PHP文档中使用它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM