php - 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.
解决方案
您正在附加一个新的整数索引元素,[]
然后添加 2 个嵌套数组。相反,将名称添加为键:
$testing[$rs['name']] = array('ip'=> $rs['ip'],
'port'=> $rs['port'],
'hosting'=> $rs['hosting']);
由于您在查询中指定了列并且它们与数组键相同,因此只需:
$testing[$rs['name']] = $rs;
推荐阅读
- android - AccessibilityService:如何“逐步”进行滚动操作?
- java - Selenium Java - 网页对话框 - 关闭对话框并退出(仅当它显示时)
- ios - TableView 在数据加载之前出现
- reactjs - 有没有办法在单个 html 文件中构建反应应用程序?
- android-studio - Android Studio 无法使用 Gradle 分发“https://services.gradle.org/distributions/gradle-4.4-all.zip”执行构建
- ruby-on-rails - ruby 中的乘法行为不同于正常的算术行为
- jquery - 通过单击链接禁用字段
- javascript - 将 Javascript 添加到 AdRolls 的点击渠道中的按钮
- matlab - Legend entries out of box
- javascript - 将整个 DIV 用作带有 onchange 的按钮来刷新内容