简体   繁体   English

如何在for循环中使用cURL?

[英]How to use cURL in for loop?

My for loop can run twice, but it only run once when I use the cURL in for loop My for loop can run twice, but it only run once when I use the cURL in for loop我的 for 循环可以运行两次,但是当我在 for 循环中使用 cURL 时它只运行一次 我的 for 循环可以运行两次,但是当我在 for 循环中使用 cURL 时它只运行一次

public function index_onSync () {

    $checkedIds = post('checked');

    $data = ModelsAdmin::select('id', 'address', 'private_key')->whereIn('id', $checkedIds)->get();

    $sync_data = array();  

    for ($i=0; $i < count($data); $i++) {

        $url_confirm = "http://127.0.0.1:50233/sync";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url_confirm);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_POST, 1);

        $post_data = array( "id"=>$data[$i]['id'], "address"=>$data[$i]['address'], "private_key"=>$data[$i]['private_key'] );
        $json_data = json_encode($post_data);

        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json',
            'Content-Length: '.strlen($json_data)
        ));

        curl_setopt($ch, CURLOPT_POSTFIELDS,$json_data);

        $data = curl_exec($ch);
        $data = json_decode($data);  
        array_push($sync_data, $data);

        echo $data;

        curl_close($ch);

    }

    var_dump($sync_data);
}

You're overriding your $data array from ModelsAdmin::select in line您正在从ModelsAdmin::select中覆盖您的$data数组

$data = curl_exec($ch);

So, on the second iteration, your data is not a 2-rows array anymore...因此,在第二次迭代中,您的数据不再是 2 行数组...
Instead of $data , you could use $response , for example...例如,您可以使用$response代替$data ......

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

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