首页 > 解决方案 > Make multidimensional array with php and pdo

问题描述

i want to edit a script i found online. is has an hardcoded array like this.

$servers = array(
    'Google Web Search' => array(
        'ip' => '',
        'port' => 80,
        'info' => 'Hosted by The Cloud',
        'purpose' => 'Web Search'
    ),
    'Example Down Host' => array(
        'ip' => 'example.com',
        'port' => 8091,
        'info' => 'ShittyWebHost3',
        'purpose' => 'No purpose'
    )
);

Result:

array(2) {
  ["Google Web Search"]=>
  array(4) {
    ["ip"]=>
    string(0) ""
    ["port"]=>
    int(80)
    ["info"]=>
    string(19) "Hosted by The Cloud"
    ["purpose"]=>
    string(10) "Web Search"
  }
  ["Example Down Host"]=>
  array(4) {
    ["ip"]=>
    string(11) "example.com"
    ["port"]=>
    int(8091)
    ["info"]=>
    string(14) "ShittyWebHost3"
    ["purpose"]=>
    string(10) "No purpose"
  }
}

I put this data in a database and want to make the same array but i dont seem to get it working

This is the code i added to make an array:

$query ="SELECT name, ip, port, hosting FROM sites";
$select = $conn->prepare($query);
$select->execute(array());
$testing = array();
while($rs = $select->fetch(PDO::FETCH_ASSOC)) {
    $testing[] = array($rs['name'] => array('ip'=> $rs['ip'], 'port'=> $rs['port'], 'hosting'=> $rs['hosting']));
}

The result from this is:

array(2) {
  [0]=>
  array(1) {
    ["Google Web Search"]=>
    array(3) {
      ["ip"]=>
      string(10) "google.com"
      ["port"]=>
      string(2) "80"
      ["hosting"]=>
      string(19) "Hosted by The Cloud"
    }
  }
  [1]=>
  array(1) {
    ["Example Down Host"]=>
    array(3) {
      ["ip"]=>
      string(11) "example.com"
      ["port"]=>
      string(2) "09"
      ["hosting"]=>
      string(14) "ShittyWebHost3"
    }
  }
}

is there a way to make the bottom array the same as the top array, i dont want to edit the whole script, this seems easier.

标签: phparraysdatabasepdo

解决方案


您正在附加一个新的整数索引元素,[]然后添加 2 个嵌套数组。相反,将名称添加为键:

 $testing[$rs['name']] = array('ip'=> $rs['ip'],
                               'port'=> $rs['port'],
                               'hosting'=> $rs['hosting']);

由于您在查询中指定了列并且它们与数组键相同,因此只需:

 $testing[$rs['name']] = $rs;

推荐阅读