我有这样的事情:
host1 | port1
host2 | port2
host3 | port3
host4 | port4
现在,我需要将对插入到数组中,以便我可以在循环中使用它们:
我试图循环遍历数组的一个值
$hosts = array('host1','host2','host3');
foreach ($hosts as $host) {
echo $host;
}
如何将对添加到数组中以便我可以调用说host
它输出主机和端口?
答案 0 :(得分:1)
您可以向数组添加数组,因此您将获得一个多维数组:
$hosts = array(array('host1', 'port1'), array('host2', 'port2'));
答案 1 :(得分:1)
您可以像这样创建数组,为每个主机创建命名密钥:
$hosts = array(
'host1' => 'port1',
'host2' => 'port2',
'host3' => 'port3'
);
(例子#1:http://www.php.net/manual/en/function.array.php)
然后你可以像这样迭代数组来获取数组键和值:
foreach($hosts as $host => $port){
echo 'This is the ' . $host;
echo 'This is the ' . $port;
}
(http://www.php.net/manual/en/control-structures.foreach.php)
答案 2 :(得分:1)
您可以使用多维数组。喜欢这个
$data= array
(
array("host1","yourport1"),
array("host2","yourport2"),
array("host3","yourport3"),
);
可以像这样访问
echo "Host: ". $data[0][0]." Port: ".$data[0][1];
答案 3 :(得分:1)
快捷方式:
// also You can define it as string directly, but I think You have a file :)
foreach(explode(PHP_EOL,file_get_contents('myIP.txt')) as $line){
$hosts[explode(' | ',$line)[0]] = explode(' | ',$line)[1];
}
var_dump($hosts);
// You will have pairs host1 => port1, host2=>port2, etc
array_walk
还有更多方法,但我懒得阅读有关array_walk
的文档。希望这个解决方案能够完全解决你的任务