如何在for循环中使用cURL?

时间:2019-01-21 11:41:30

标签: php

我的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);
}

1 个答案:

答案 0 :(得分:0)

您要从$data行中覆盖ModelsAdmin::select数组

$data = curl_exec($ch);

因此,在第二次迭代中,您的数据不再是2行数组...
例如,您可以使用$data代替$response ...