Home > Software engineering >  How to rearrange this array
How to rearrange this array

Time:12-28

I have one question about PHP coding!

I want to send data to Google sheets, and all works well, I made an app!

I grab data from my app, and send data to sheets, but transferred data isn't sorted well.

The code is below:

foreach($processor->maildata As $data){
    if( in_array($data[_FF_DATA_TITLE].$data[_FF_DATA_ID], $bffields) ){
        $rowData[] = [$data[_FF_DATA_VALUE]];
    }
}

I getting data as $rowData[]=[["test"],["test"],["test"]] but they should be sortet as $rowData[]=[["test","test","test"]].

I always get data in sheets one below the other in A1 row, but they should be sorted in sheets row by row (A,B,C..)

I hope I explained it well! Any help! Regards

CodePudding user response:

By using the [] around the $data[_FF_DATA_VALUE] you are actually telling PHP to add the value from the data array into a new array.

If you want:

  • $rowData to contain one array (the row)
  • and this array to contain the values (e.g. test)

.. you should simply omit the [] around the data array like this:

foreach($processor->maildata As $data){
    if( in_array($data[_FF_DATA_TITLE].$data[_FF_DATA_ID], $bffields) ){
        $rowData[] = $data[_FF_DATA_VALUE];
    }
}

CodePudding user response:

I solved my problem, the soluction is:

foreach($processor->maildata As $data){
              if( in_array($data[_FF_DATA_TITLE].$data[_FF_DATA_ID], $bffields) ){

              $rowData[]=$data[_FF_DATA_VALUE];
            
              }
            
            }

$requestBody = new Google_Service_Sheets_ValueRange(['values' => [$rowData]]);

           $params =['valueInputOption' => 'RAW'];
           $insert=["valueDataOption" => "INSERT_RAW"];
           $this->response = $this->service->spreadsheets_values->append($gdata->spreadsheet_id, $range, $requestBody, $params,  $insert);

In this part of code:

before:

  $requestBody = new Google_Service_Sheets_ValueRange(['values' => $rowData]);

now:

      $requestBody = new Google_Service_Sheets_ValueRange(['values' => [$rowData]]);

I wrapped "$rowData" with brackets "[]" and it is it!

I got the desired solution, and the data was properly sorted on the sheet!

  • Related