簡體   English   中英

識別 PHP mysqli_fetch_row() WHILE 循環中的列號

[英]identifying column number in PHP mysqli_fetch_row() WHILE loop

我試圖確定我是否正在查看數組中的第一列。

我什么都沒試過,但是google了很多,找不到解決辦法。

while($row = mysqli_fetch_row($sql)) {
    echo '<tr>'; 
    foreach ($row as $col) {
        if () //NEED CODE HERE
        echo "<td><a href = 'https://whatismyipaddress.com/ip-lookup' target = '_blank'>$col</a></td>";
    }
    echo '</tr>';
}

mysqli_fetch_row從結果集中獲取“一行數據並將其作為枚舉數組返回,其中每列存儲在從 0(零)開始的數組偏移量中。” 因此列的鍵與列順序相同。

所以你可以這樣做:

while($row = mysqli_fetch_row($sql)) {
    echo '<tr>'; 
    foreach ($row as $key => $col) {
        if ($key === 0) {
          echo "<td><a href = 'https://whatismyipaddress.com/ip-lookup' target = '_blank'>$col</a></td>";
        }
    }
    echo '</tr>';
}

但列受數據庫結構變化和 SQL 查詢變化的影響。 我個人更喜歡mysqli_fetch_assocmysqli_fetch_object ,所以我可以按名稱而不是訂單號使用列。 它不易出錯。 例如,

while($row = mysqli_fetch_assoc($sql)) {
    echo '<tr>'; 
    foreach ($row as $key => $col) {
        if ($key === 'ip_address') {
          echo "<td><a href = 'https://whatismyipaddress.com/ip-lookup' target = '_blank'>$col</a></td>";
        }
    }
    echo '</tr>';
}

注意:這里的$sql應該是mysqli_query結果而不是實際的 SQL 字符串。

類型:1你可以使用array_key_first

foreach($row as $key => $value){
    if ($key === array_key_first($row)){
    echo 'FIRST ELEMENT!';
    }  
}

類型:2您也可以使用密鑰。

foreach($row as $key => $value){
    if ($key === 0){
    echo 'FIRST ELEMENT!';
    }  
}

類型:3第一次你會得到真實,然后它會是錯誤的。

$first = true; 
foreach ($row as $key => $value)
{
  if ( $first )
  {
    // do something
    $first = false; //in order not to get into the if statement for the next loops
  }
  else
  {
    // do something else for all loops except the first
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM