0

I have this db

id | domain    | whois_server         |
---------------------------------------
1  | ac        | whois.nic.ac         |
2  | ae        | whois.nic.ae         |
3  | id        | whois.pandi.or.id    |

How to show array form array without id ?

array (
    'ac' => 'whois.nic.ac',
    'ae' => 'whois.nic.ae',
    'id' => 'whois.pandi.or.id',
)

I have done the following code:

$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])));
}

but what appears is :

array (
    [0] => whois.nic.ac
    [1] => whois.nic.ae
    [2] => whois.pandi.or.id
)
Qirel
  • 25,449
  • 7
  • 45
  • 62
Muhammad Rifky
  • 75
  • 1
  • 12

5 Answers5

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);
CodeZi.pro
  • 229
  • 5
  • 8
1

In your loop you can add the key to the $whoisseervers variable for each value:

$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);
Jerodev
  • 32,252
  • 11
  • 87
  • 108
1
$whoisservers = array();
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
  $whoisservers[$row["domain"]] = $row["whois_server"];
}

would be simpler (and clearer).

And as mentioned in the comments, in the SQL don't select fields you don't need.

ADyson
  • 57,178
  • 14
  • 51
  • 63
1

Add to the $whoisservers array, by pushing the index as $row['domain'] and the value as $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);
Qirel
  • 25,449
  • 7
  • 45
  • 62
1

A little different from other answers solution with fetchAll and 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);
u_mulder
  • 54,101
  • 5
  • 48
  • 64