有人可以帮助我如何在我的while循环中获取我的MySQL列名吗? 我的代码是这样的:
if (mysqli_connect_errno()) {
echo "MySQL failed: " . mysqli_connect_errno();
}
if (isset($_GET['date'])) {
$get_date = $_GET['date'];
$result = mysqli_query($conn, "SELECT * FROM stats WHERE form_date = '$get_date'");
$col = array();
while ($row = mysqli_fetch_array($result)) {
$col[] = $row['year'];
$col[] = $row['month'];
$col[] = $row['day'];
$col[] = $row['weekday'];
$col[] = $row['form_date'];
$col[] = $row['name'];
$col[] = $row['count'];
$col[] = $row['lang'];
}
echo "<pre>";
print_r($col);
echo "</pre>";
mysqli_close($conn);
} else {
echo "Please set a date value in URL parameter ?date=[YYYY-MM-DD]";
}
我返回的数组看起来像这样:
Array
(
[0] => 2014
[1] => 01
[2] => 01
[3] => Wednesday
[4] => 2014-01-01
[5] => Michael K
[6] => 41
[7] => SE
[8] => 2014
[9] => 01
[10] => 01
[11] => Wednesday
[12] => 2014-01-01
[13] => Nicklas S
[14] => 40
[15] => DK
[16] => 2014
[17] => 01
[18] => 01
[19] => Wednesday
[20] => 2014-01-01
[21] => Jesper S
[22] => 5
[23] => SE
)
但是我想让我的数组像这样返回:
Array
(
[year] => 2014
[day] => 01
[month] => 01
[weekday] => Wednesday
[form_date] => 2014-01-01
[name] => Michael K
[count] => 41
[lang] => SE
[year] => 2014
[month] => 01
[day] => 01
[weekday] => Wednesday
[form_date] => 2014-01-01
[name] => Nicklas S
[count] => 40
[lang] => DK
[year] => 2014
[month] => 01
[day] => 01
[weekday] => Wednesday
[form_date] => 2014-01-01
[name] => Jesper S
[count] => 5
[lang] => SE
)
因此,我的数组中的键与我在数据库中的列名相匹配。 我似乎无法理解我是如何做到这一点的。有人可以帮忙吗? : - )
答案 0 :(得分:2)
更改
$col = array();
while ($row = mysqli_fetch_array($result)) {
$col[] = $row['year'];
$col[] = $row['month'];
$col[] = $row['day'];
$col[] = $row['weekday'];
$col[] = $row['form_date'];
$col[] = $row['name'];
$col[] = $row['count'];
$col[] = $row['lang'];
}
到
$col = array();
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$col[] = $row;
}
print_r($col);
mysql_fetch_array()有第二个论点。此可选参数是一个常量,指示应从当前行数据生成哪种类型的数组。此参数的可能值是常量MYSQLI_ASSOC,MYSQLI_NUM或MYSQLI_BOTH。
答案 1 :(得分:0)
您正在寻找mysqli_fetch_assoc()
,它将结果作为关联数组(column =&gt; value)。
然后试试这个:
while ($row = mysqli_fetch_assoc($result)) {
echo "<pre>";
print_r($row);
echo "</pre>";
}
答案 2 :(得分:0)
您不能使用这样的关联数组,因为它将具有重复的键索引,这是不允许的。我建议你使用重组数组来让每个&#34;组&#34;键作为嵌套数组。
答案 3 :(得分:-1)
使用mysql_assoc_array()
代替mysq_fetch_array()