dongqian2021
dongqian2021
2013-11-16 01:57

PHP foreach行为$ var,行名和行号重复[duplicate]

已采纳

This question already has an answer here:

I coded a simple function to loop trough and display all variables in the sql table. However foreach $row displays the rows two times, 1 time as a row name and 1 time as a row number.

1 : $row['NAME'] Name form

2 : $row[0]' Number form

PHP :

<?php

include "condetails.php";
$query = "select * from pagedetails";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
  foreach($row as $var => $val) {
    echo "VARNAAM :".$var;
    echo "<br />";
    echo "VALUE".$val;
    echo "<br />";
    echo "<br />";
  }
}

?>

OUTPUT :

VARNAAM :0 VALUE1

VARNAAM :id VALUE1

VARNAAM :1 VALUEdddd

VARNAAM :h1txt VALUEdddd

</div>
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

3条回答

  • doukuang1897 doukuang1897 8年前

    It's displayed twice because mysql_fetch_array() grabs the column name and its number.

    If you want just the column names try using mysql_fetch_assoc(), keep in mind mysql_* functions are depreciated and you should be using PDO / MySQLi :)

    点赞 评论 复制链接分享
  • douketangyouzh5219 douketangyouzh5219 8年前

    From the manual:

    mysqli_fetch_array() is an extended version of the mysqli_fetch_row() function. In addition to storing the data in the numeric indices of the result array, the mysqli_fetch_array() function can also store the data in associative indices, using the field names of the result set as keys.

    What you you're really looking for is mysqli_fetch_assoc():

    Returns an associative array that corresponds to the fetched row or NULL if there are no more rows.

    点赞 评论 复制链接分享
  • duandu1915 duandu1915 8年前

    mysql_fetch_array returns a mixed array with keys as numbers and as column names. You probably want mysql_fetch_assoc(), which only returns the name keys.

    点赞 评论 复制链接分享