Search code examples
phparraysloops

PHP loop is overwriting array


I have loop inception going on and I could use some help please.

I have to loop through some curl calls to an API, and get the records to then push to another API. Each call from this endpoint returns only 30 records, so I also need to loop through if there are more than 30.

I am trying to dump out an array at the end of all loops to see what I thought would be all the data, but it is only outputting 1 record.

Am I missing something dumb here?

$project_ids = array(
    '111111',
    '222222',
    );

$array = array();

foreach ($project_ids as $proj_id) {

    $go_again = true;
    $page = 1;
    $per_page = 30;

    while ( $go_again ) {

        $curl = curl_init($baseurl . $key_url);

        $keyPOSTdata = array(
            "date_format" => "d-m-Y",
            "page" => $page,
            "projects_id" => $proj_id,
        );

        curl_setopt($curl, CURLOPT_POST, false);
        curl_setopt($curl, CURLOPT_HEADER, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($keyPOSTdata));
        curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));

        $response = curl_exec($curl);

        $result = json_decode($response);
        $total =  $result->body->total_count;
        $new_total = $total - ($per_page * $page);

        if( $total - ($per_page * $page ) > 0 ) {
            ++$page;
        }
        else {
            $page = 1;
            $go_again = false;
        }

        curl_close($curl);

        foreach ($result->body as $item) {
            $array['attribute1'] = $item->attribute1;
            $array['attribute2'] = $item->attribute2;
            $array['attribute3'] = $item->attribute3;
        }

    }

}

echo '<pre>';
print_r($array);
echo '</pre>';
exit();

Solution

  • You are, indeed, rewriting the array on each loop. Notice you don't initialize a new row for each record, you're only writing on the "attributeX" field over and over. This should work:

    foreach ($result->body as $item) {
        $record = [];
        $record['attribute1'] = $item->attribute1;
        $record['attribute2'] = $item->attribute2;
        $record['attribute3'] = $item->attribute3;
        $array[] = $record;
    }