我有这个数据库
id | domain | whois_server |
---------------------------------------
1 | ac | whois.nic.ac |
2 | ae | whois.nic.ae |
3 | id | whois.pandi.or.id |
如何显示不带id的数组形式的数组?
array (
'ac' => 'whois.nic.ac',
'ae' => 'whois.nic.ae',
'id' => 'whois.pandi.or.id',
)
我已完成以下代码:
$sql = "SELECT * FROM whois_server ";
$result = $db->prepare($sql);
$result->execute();
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
$whoisservers = array_merge($whoisservers, array_map('trim', explode(",", $row[1])));
}
但是出现的是:
array (
[0] => whois.nic.ac
[1] => whois.nic.ae
[2] => whois.pandi.or.id
)
答案 0 :(得分:2)
$sql = "SELECT * FROM whois_server ";
$result = $db->prepare($sql);
$result->execute();
$dataReturn = [];
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
$dataReturn[$row['domain']] = $row['whois_server'];
}
print_r($dataReturn);
答案 1 :(得分:1)
在循环中,您可以为每个值将密钥添加到$whoisseervers
变量中:
$sql = "SELECT domain, whois_server FROM whois_server";
$result = $db->prepare($sql);
$result->execute();
$whoisservers = [];
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
$whoisservers[$row['domain']] = $row['whois_server'];
}
print_r($whoisservers);
答案 2 :(得分:1)
$whoisservers = array();
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
$whoisservers[$row["domain"]] = $row["whois_server"];
}
将更简单(更清晰)。
并且如注释中所述,在SQL中不要选择不需要的字段。
答案 3 :(得分:1)
通过将索引按$whoisservers
和值按$row['domain']
的形式添加到$row['whois_server']
数组中。
$whoisservers = [];
$sql = "SELECT * FROM whois_server ";
$result = $db->prepare($sql);
$result->execute();
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
$whoisservers[$row['domain']] = $row['whois_server'];
}
print_r($whoisservers);
答案 4 :(得分:1)
与其他使用fetchAll
和PDO::FETCH_KEY_PAIR
的答案解决方案略有不同:
$sql = "SELECT domain, whois_server FROM whois_server";
$result = $db->prepare($sql);
$result->execute();
$whoisservers = $result->fetchAll(PDO::FETCH_KEY_PAIR);
print_r($whoisservers);