php - 在特定条件下重做最后一个 foreach 循环命令

标签 php web-services loops foreach error-handling

我们正在向网络服务发出 1000 次请求。每次我们发出请求时,我们都希望得到响应,但有时 Web 服务会失败并且不提供响应。发生这种情况时,我们希望休眠 30 秒,然后在它失败的最后一点重新运行该循环。如何才能做到这一点?

这是基本结构:

foreach ( $objects as $object ) {
    foreach ( $otherObjects as $otherObject ) {

        //Prepare request data from $object and $otherObjects

        //Send request to webservice using cURL

        //Receive response and check to see if success
        if ( isset( $response ) ) {
            //Save response to database
        } else {
            //Not successful. Sleep for 30 seconds. Send request again up to 3 times. If ultimately successful continue, if not break and alert system admin.
        }
    }
}

最佳答案

您可以将请求分解为一个函数:

foreach ( $objects as $object ) {
    foreach ( $otherObjects as $otherObject ) {
        $tries = 0;
        //Receive response and check to see if success.
        while( ($response = doRequest($object, $otherObject)) === false && $tries < 3) {
            //Not successful. Sleep for 30 seconds. Send request again up to 3 times.
            $tries++;
            sleep(30);
        }
        if ( $response ) {
            //Successful save response to database.
        } else {
            //Not successful break and alert system admin.
    }
}

function doRequest($object, $otherObject) {
    //Prepare request data from $object and $otherObject.
    //Send request to webservice using cURL.

    return $result;
}

关于php - 在特定条件下重做最后一个 foreach 循环命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29378333/

相关文章:

c# - 将 xml 数据发送到 Web 服务而不是使用 CDATA 的最佳方法是什么?

c - 仅循环第一个和最后一个元素

Python:创建循环来更新数据

arrays - 紧急运行时错误索引超出范围 [3],长度为 3

PHP mySQL 查询返回单个字段作为 2 元素数组

php - 拉拉维尔 : Property [name] does not exist on this collection instance

php - 无法创建存储过程 mysql 可能是 if else 语法

php - MySQL检查表是否已经存在

android - 为每隔几秒发出一次请求的android应用程序创建服务器端

c# - 'Service Reference' 和 'Web Reference' 之间的不同行为