在数组条目之间切换

时间:2014-02-05 12:37:13

标签: php arrays

我正在编写一个与外部API接口的应用程序。我们有五个API客户端(为了处理更多请求 - 在API T& C下允许),这些请求存储在一个数组中。我们有另一组对象,我们使用foreach执行操作。

例如:

$clients = array(
    array(
        "key" => "somekey",
        "secret" => "somesecret"
    ),
    array(
        "key" => "somekey",
        "secret" => "somesecret"
    ),
    array(
        "key" => "somekey",
        "secret" => "somesecret"
    )
);

接下来,我们有一个要处理的对象数组:

$objects = array(
    array(
        "info" => "someinfo",
        "url" => "someurl",
        "id" => 1234,
        "more" => "more"
    ),
    array(
        "info" => "someinfo",
        "url" => "someurl",
        "id" => 1234,
        "more" => "more"
    ),
    array(
        "info" => "someinfo",
        "url" => "someurl",
        "id" => 1234,
        "more" => "more"
    )
);

因此,要使用一个API密钥处理它们,我们会执行以下操作:

foreach($objects as $object){
     $class->setAPIKey($clients[0]);
     $result = $class->process($object);
}

为了使用多个键处理它们,我们尝试了这个:

$key = 0;
foreach($objects as $object){
    $class->setAPIKey($clients[$key]);
    $result = $class->process($object);
    if($key + 1 == sizeof($clients)){
        $key = 0;
    } else {
        $key++;
    }
}

这有效,但似乎效率不高。是否有更快/更小的方法来做同样的事情?

1 个答案:

答案 0 :(得分:0)

你可以这样试试:

foreach($objects as $key => $object){
     $class->setAPIKey($clients[$key]);
     $result = $class->process($object);
}