我已将所有数据保存到数组中,并希望获得所提供“代码”的“名称”。
如何获取该代码的数组行?
另外,这是最有效的过程吗?
id | code | name |
__________________________
1 | KNTY | Kentucky |
2 | PURD | Purdue |
3 | TEXS | Texas |
// Move data to array
$search = "SELECT * FROM table";
$query = mysqli_query($conn, $search);
while($row = mysqli_fetch_assoc($query)) {
$array[] = $row;
}
// Code I want a name for
$code = "KNTY";
// MYSTERY STEP I NEED HELP WITH
$name = $array[$id]['name'];
答案 0 :(得分:1)
我使用itachi的评论提示进行编辑。您可以使用code
作为$array
:
$search = "SELECT * FROM table";
$query = mysqli_query($conn, $search);
$array = array();
while($row = mysqli_fetch_assoc($query)) {
$array[$row['code']] = $row['name'];
}
// Code I want a name for
$code = "KNTY";
$name = $array[$code];
答案 1 :(得分:1)
是的,您可以执行类似的操作,而在获取循环内,将code
指定为关键字。这必须是唯一的:
$search = 'SELECT * FROM table_name';
$query = mysqli_query($conn, $search);
while($row = mysqli_fetch_assoc($query)) {
// assign `$row['code']` as key to this rowset
$array[$row['code']] = $row;
}
$code = 'KNTY';
if(isset($array[$code])) { // add some checking, you wouldn't want undefined index errors
$name = $array[$code]['name'];
echo $name;
} else {
echo 'Sorry not found';
}