简体   繁体   English

如何针对数组同时运行PHP函数?

[英]How to run a PHP function concurrently against an array?

I have a PHP web app which scrapes a search engine for a given keyword. 我有一个PHP Web应用程序,用于搜索给定关键字的搜索引擎。

Currently the app is looping through an array of keywords running the scrape function one keyword at a time. 目前,该应用程序正在遍历一系列关键字,这些关键字一次运行一个scrape函数。

This is OK at the moment because the number of keywords is fairly small, but it won't scale well. 目前可以这样做,因为关键字数量很少,但是扩展性不佳。

I think the best way to go will be to select a smaller set of keywords from the mysql db using limit, and then run the scrape function concurrently against the entire array. 我认为最好的方法是使用limit从mysql db中选择一组较小的关键字,然后对整个数组同时运行scrape函数。 Once that set has finished, I'll move on to the next set. 一旦完成,我将继续下一组。

But I'm stuck with how to run the function concurrently against the array. 但我仍然坚持如何同时对阵列运行该函数。

How would you handle this? 你会怎么处理这个?

PHP本身没有任何并发​​性,但如果使用cURL获得搜索结果,则cURL扩展中会有多个请求功能 ,因此您可以并行化至少获取结果。

<?php
$fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple");

function test_alter(&$item1, $key, $prefix)
{
    $item1 = "$prefix: $item1";
}

function test_print($item2, $key)
{
    echo "$key. $item2<br />\n";
}

echo "Before ...:\n";
array_walk($fruits, 'test_print');

array_walk($fruits, 'test_alter', 'fruit');
echo "... and after:\n";

array_walk($fruits, 'test_print');
?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM