是否可以一次对阵列的所有成员执行一个函数?

时间:2017-05-03 03:12:32

标签: php arrays function asynchronous foreach

背景:

$a = array('1','2','3');
foreach ($a as $item){
  //rest of code
  //example file_get_contents(url);
  //the script waits for it to be completed before going to the next
}

以上脚本逐一进行。

我担心的是,当单个元素上的进程花费太长时,其余元素必须等待处理。

是否可以同时对所有数组项执行 stuff

1 个答案:

答案 0 :(得分:0)

做一些搜索我发现滚动卷曲 https://github.com/joshfraser/rolling-curl

我拿了包含的example.php,我把它缩短了一点

require("RollingCurl.php");
$urls = array(); // regular array, or from csv or from Database...

function request_callback($response, $info) {
    // parse the page title out of the returned HTML
    if (preg_match("~<title>(.*?)</title>~i", $response, $out)) {
        $title = $out[1];
    }
    echo "<b>$title</b>";
    print_r($info);
    echo "<hr>";
}

$rc = new RollingCurl("request_callback");
$rc->window_size = 20;
foreach ($urls as $url) {
    $request = new RollingCurlRequest($url);
    $rc->add($request);
}
$rc->execute();