用php和pdo制作多维数组
我想编辑我在网上找到的脚本。is有一个这样的硬编码数组用php和pdo制作多维数组,php,arrays,database,pdo,Php,Arrays,Database,Pdo,我想编辑我在网上找到的脚本。is有一个这样的硬编码数组 $servers = array( 'Google Web Search' => array( 'ip' => '', 'port' => 80, 'info' => 'Hosted by The Cloud', 'purpose' => 'Web Search' ), 'Example Down Host' => a
$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'
)
);
结果:
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"
}
}
我把这些数据放在一个数据库中,想制作相同的数组,但我似乎无法让它工作
这是我为创建数组而添加的代码:
$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']));
}
其结果是:
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"
}
}
}
是否有办法使底部数组与顶部数组相同,我不想编辑整个脚本,这似乎更容易。您正在使用
[]
添加一个新的整数索引元素,然后添加两个嵌套数组。而是添加名称作为密钥:
$testing[$rs['name']] = array('ip'=> $rs['ip'],
'port'=> $rs['port'],
'hosting'=> $rs['hosting']);
由于您在查询中指定了列,并且这些列与数组键相同,因此只需执行以下操作:
$testing[$rs['name']] = $rs;
为数组赋值时,使用语法
$arr[key]=$value
。如果在赋值过程中忽略该键,$value
将被赋值给数组的下一个可用整数键,从0开始。
这是一个如何工作的示例:
$arr = array();
$arr[] = 'one';//Empty, so insert at 0 [0=>'one']
$arr[] = 'two';//Last element at 0, so use 1 [0=>'one',1=>'two']
$arr[6]= 'three';//Key is used, so use key [0=>'one',1=>'two',6=>'three']
$arr[] = 'four';//Max used integer key is 6, so use 7
print_r($arr);//[0=>'one',1=>'two',6=>'three',7=>'four']
因此,当您在代码中使用
$testing[] = array(
$rs['name'] => array(
'ip'=> $rs['ip'],
'port'=> $rs['port'],
'hosting'=> $rs['hosting']
)
);
您正在将新创建的数组分配到位置0,1,2,…N
为了避免这种情况,只需使用您真正想要的值显式指定键,如
$testing['name'] => array(
'ip'=> $rs['ip'],
'port'=> $rs['port'],
'hosting'=> $rs['hosting']
);
您可以在中阅读有关阵列的更多信息
旁注
如果您不介意在生成的数组中有一个额外的列,您可以这样完全重写代码:
$query ="SELECT name, ip, port, hosting FROM sites";
$results = $conn->query($query)->fetchAll(PDO::FETCH_ASSOC);
$testing = array_column($results,null,'name');
它稍微慢一点,但在我看来非常方便,PDOStatement::fetchAll
一次检索所有数据,array\u column
使用null
作为第二个参数,并使用想要的列作为键重新索引数组