在PHP中爆炸数组值
I'm working on a script that connects to a server using proxies, going through the list until it finds a working proxy.
The list of proxies is like this:
127.0.0.1:8080
127.0.0.1:8080
127.0.0.1:8080
127.0.0.1:8080
127.0.0.1:8080
127.0.0.1:8080
127.0.0.1:8080
Of course, it's not the same IP and port over and over. Now, originally I was just going to use file()
to put them all into an array, but that leaves an array with the values including the full line, obviously.
Ideally what I'd like is an array like
"127.0.0.1" => 8080,
"127.0.0.1" => 8080,
"127.0.0.1" => 8080,
"127.0.0.1" => 8080,
"127.0.0.1" => 8080,
"127.0.0.1" => 8080,
"127.0.0.1" => 8080,
"127.0.0.1" => 8080,
But I'm not sure of the easiest (and most efficient) way to do that. Any suggestions?
我正在编写一个脚本,使用代理连接到服务器,遍历列表直到找到工作状态 代理。 p>
代理列表如下: p>
127.0.0.1:8080
127.0.0.1:8080
127 .0.0.1:8080
127.0.0.1:8080
127.0.0.1:8080
127.0.0.1:8080
127.0.0.1:8080
代码> PRE>
当然,它不是一遍又一遍的IP和端口。 现在,我最初只是使用 file() code>将它们全部放入一个数组中,但显然会留下一个包含完整行的值的数组。 p>
理想情况下,我喜欢的是像 p>
“127.0.0.1”=>这样的数组。 8080,
“127.0.0.1”=> 8080,
“127.0.0.1”=> 8080,
“127.0.0.1”=> 8080,
“127.0.0.1”=> 8080,
“127.0.0.1”=> 8080,
“127.0.0.1”=> 8080,
“127.0.0.1”=> 8080,
code> pre>
但我不确定最简单(也是最有效)的方法。 有什么建议吗? p>
div>
Loop over the file and do some parsing:
$path = './file.txt';
$proxies = array();
foreach(file($path, FILE_SKIP_EMPTY_LINES) as $line) {
$proxy = trim($line);
list($ip, $port) = explode(':', $proxy);
$proxies[$ip] = $port;
}
var_dump($proxies);
Should note that your 'expected' example is invalid array notation as the key is the same for every element. But I just assumed you were going for formatting.
Use Following Code
<?php
$data = "127.0.0.1:8080
127.0.0.1:8080
127.0.0.1:8080
127.0.0.1:8080
127.0.0.1:8080
127.0.0.1:8080
127.0.0.1:8080";
$urls = explode("
",$data);
$new_data = array();
foreach($urls as $url){
if($url!=""){
$url_parts = explode(":",$url);
$new_data[] = array($url_parts[0]=>$url_parts[1]);
}
}
print_r($new_data);
?>