[英]Database Query into Associative Array using PHP
I am trying to grab data from my database and place in a format so I can call field1 and return field2. 我试图从数据库中获取数据并以某种格式放置,以便可以调用field1并返回field2。
In my mind I think this: 我认为这是:
while($row = mysqli_fetch_assoc($result)) {
$aa = $row["field1"];
$bb = $row["field2"];
}
$cc = array(“$aa”=>”$bb”);
Will compute this: 将计算此:
$cc = array(
"Row1a"=>"Stuff in field2 row1b",
"Row2a"=>"Stuff in field2 Row2b",
"Row3a"=>"Stuff in field2 Row3b",
"Row4a"=>"Stuff in field2 Row4b",
);
After this I will be able to: 之后,我将能够:
echo $cc('Row1a');
To display: 显示:
Stuff in field2 row1b
Please try this and let me know if it meets your requirements 请尝试一下,让我知道它是否符合您的要求
<?php
$result=NULL;
while($row = mysqli_fetch_assoc($result)) {
$aa = $row["field1"];
$bb = $row["field2"];
$result[$aa]=$bb;
}
echo $result['Row1a'];
?>
Edited code Then this should meet your requirement 编辑的代码然后这应该满足您的要求
<?php
$search=$_POST['userText'];
$query= "SELECT * FROM table WHERE field1='".$search."';";
$result=mysql_query($query,$con);
$output=NULL;
if(mysql_num_rows($result)>0) //to check if at least 1 match found
{
$array=mysql_fetch_array($result);
$output=$array['field2'];
}
if(isset($output))
echo $output; // can be returned as needed
else
echo 'No match found';
?>
Here's one way. 这是一种方法。 If there aren't an even number of elements in
$row
then the odd last one will be set to Last
. 如果
$row
中没有偶数个元素,则将奇数个last设置为Last
。 But obviously this overwrites $result
each time so you probably want a multidimensional array using a counter and $result[$i]
or some such: 但是显然,这每次都会覆盖
$result
因此您可能希望使用一个计数器和$result[$i]
或类似的多维数组:
foreach(array_chunk($row, 2) as $pair) {
if(isset($pair[0], $pair[1])) {
$result[$pair[0]] = $pair[1];
}
}
if(isset($pair[0])) {
$result['Last'] = $pair[0];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.