我使用以下内容将数据库中的所有数据放入数组中。
$query = "SELECT * FROM images ORDER BY id ASC";
$result = mysqli_query($link, $query);
$row = $result->fetch_array();
我通常使用while循环遍历数组并对数据执行某些操作。在这种情况下,我需要从数据库中手动选择某些行,但不使用多个查询。如何选择例如行名称为“image”的数组中的第三个结果?
我确定我以前做过这个,但不记得怎么做。我尝试使用像$row['image'][3]
这样的代码,但这只是第三个字母。
感谢。
答案 0 :(得分:1)
您可以将所有结果强制转换为数组,然后将索引号用作行。
$query = "SELECT * FROM images ORDER BY id ASC";
$result = mysqli_query($link, $query) or die("Error!.." . mysqli_error($link));
$rows = array();
$rows[0] = ''; // For sake of readability and usability we fill the first index with nothing, this way the first row will be saved in the [1] index.
while($row = $result->fetch_array()){
$rows[] = $row;
}
然后,您可以使用$rows[5]['columnname'];
答案 1 :(得分:0)
$query = "SELECT * FROM images ORDER BY id ASC" or die("Error!.." .mysqli_error($link));
$result = mysqli_query($link, $query);
$row = $result->fetch_array();
$thirdcol= $row['2'];
echo $thirdcol;
你走了。
或者您可以使用$row['ColName'];
例如:$row['StackoverFlow'];
答案 2 :(得分:0)
试试这个:http://www.weberdev.com/get_example.php3?ExampleID=1628
<?php
/*==================================
Author : Lord Nightslave
in_aeternum@hotmail.com
Load a query result into two dimensional array.
You can later refer the result in an array form with
the original field name.
i.e print $myresultarray[$i]["My Table Field Name"]
====================================*/
?>
<?php
/* You can put this in other file and just include it */
function OpenDb($hostname,$uid,$pwd,$dbname){
$link = @mysql_pconnect($hostname,$uid,$pwd);
if($link && mysql_select_db($dbname)){
return($link);
}
else{
return(FALSE);
}
}
?>
<?php
function QueryIntoArray($query){
settype($retval,"array");
$result= mysql_query($query);
if(!$result){
print "Query Failed";
}
for($i=0;$i<mysql_numrows($result);$i++){
for($j=0;$j<mysql_num_fields($result);$j++){
$retval[$i][mysql_field_name($result,$j)] = mysql_result
($result,$i,mysql_field_name($result,$j));
}//end inner loop
}//end outer loop
return $retval;
}//end function
?>
<!--An Example How To Use The functions
To try it simple change the appropriate variable to your own database & tables
-->
<HTML>
<HEAD>
<TITLE>PHP Array Test</TITLE>
</HEAD>
<BODY BGCOLOR=WHITE>
<?php
OpenDb("myhost","myuid","mypwd","mydatabase") or die("Failed Opening Database");
settype($myresult,"array");
$query = "SELECT * FROM mytable";
$myresult = QueryIntoArray($query);
for($i=0;$i<count($myresult);$i++){
print $myresult[$i]["MyField1"];
print $myresult[$i]["MyField2"];
}
?>
</BODY>
</HTML>
答案 3 :(得分:0)
$found = false;
while (!$found && $index < $row.length) {
if ($row[$index] === IMAGE_NAME) {
++$count;
} else if ($row[$index] === IMAGE_NAME && $count < THIRD_MATCH ) {
$found = true;
$match = $row[$index];
}
++$index;
}