显示数据库中的数组

时间:2019-03-22 15:53:03

标签: php mysql sql arrays pdo

我有这个数据库

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
)

5 个答案:

答案 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)

与其他使用fetchAllPDO::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);