-1

I am trying to store the values from the foreach into one variable. But i can't seem to get it to work:

    foreach ($chunks as $key)   {
      // Get the Excel template path
      $path = storage_path('/app/excel/331-3-17 72AN - 21.3 - Ст. 20.xlsx');

      // Load the excel template file
      Excel::load($path, function($reader) use (&$key) {

      // Load the Excel sheet
      $objExcel = $reader->getExcel();
      $sheet = $objExcel->getSheet(0);

        foreach ($key as $row) {

           $welds = $row->weld;

           $string .= $welds.',';

      }

    $sheet->getCell('B25')->setValue($string);

    })
    // Set filename & store it
    ->setFilename("331-3-17 72AN - 21.3 - Ст. 20 " . date("d.m.y").'-'.mt_rand())
    ->store('xlsx', storage_path('/app/exports/21.3 - 2.5 - Ст20 '.date('m-d-Y')));
  }

Result I get is:

КСС1814.

Expected result as one string is:

КСС1810, КСС1811, КСС1812, КСС1813, КСС1814

enter image description here enter image description here

The M
  • 621
  • 1
  • 7
  • 29
  • If there is outer loop then show code for that also – B. Desai Nov 30 '17 at 07:30
  • update total code – K.K Nov 30 '17 at 07:31
  • where is $string initiated? – laiju Nov 30 '17 at 07:31
  • 3
    This code is pointless. Just use [`implode`](http://php.net/manual/en/function.implode.php) to add commas to an array. You can extract the values from that initial array, then join them together. – tadman Nov 30 '17 at 07:33
  • the result will have a trailing comma at the end if you do it this way. why not just collect the welds in an array and implode? – Gordon Nov 30 '17 at 07:34
  • How can your result be a dot after `КСС1814` when your code adds a comma? Are you sure this code is related to the output? – Andreas Nov 30 '17 at 07:40
  • updated the code – The M Nov 30 '17 at 07:40
  • Also added another image to make it more clear. I have 1 query that takes the data. this is chunked into arrays of 5. From each array that consist of 5 i need to put the weld (КСС1814) into 1 variable/string so i can place all 5 welds into a excel cell. – The M Nov 30 '17 at 07:46

1 Answers1

3

Not sure if this is correct but it's a guess.
Use array column and implode with comma.

$welds = array_column($key, "weld");
$string = implode(",", $welds);

Array_column will grab all values in the array key where the key is "weld".
Implode will build a string of the array with commas between the values.

Andreas
  • 23,304
  • 5
  • 28
  • 61