Skip to content
Advertisement

PHP: Invalid argument supplied for foreach() while dynamic data Export?

Getting error while Printing dynamic data in phpexcel – Error Invalid Argument while printing data from my MYSQL Database

$labels = array();
$i = 0;
while ($row1 = mysql_fetch_array($query_result1, MYSQL_ASSOC)) {
    $labels[$i++] = $row1["label"];
} 
  foreach($labels[0] as $ind=>$label){ //error invalid argument
        $letter = range('A', 'Z')[$ind];
        $tmp = explode('>',$label); 
        $col_names[] = $tmp[0];
        echo $letter.'1'."rn";

        echo "Column -> $tmp[0] rn"; 
}  

    foreach ($labels as $ind=>$item){ //Error invalid Argument

    $index = $ind + 2;

foreach($item as $ind2=>$data){

      $letter = range('A', 'Z')[$ind2];

    $val = explode('>',$data);

    $objPHPExcel->getActiveSheet()->setCellValue("$letter$index",$val[1]);

}

} 

My Var_dump($labels) output is

  array(15) {
  [0]=>
  string(2) "EY"
  [1]=>
  string(3) "PWC"
  [2]=>
  string(8) "Deloitte"
  [3]=>
  string(4) "KPMG"
  [4]=>
  string(14) "Grant Thornton"
  [5]=>

I Added my Whole Code Please Once Please

it is giving invalid argument error

Advertisement

Answer

As mentioned in the comments, $labels[0] is not an array, $labels however is.

Change:

foreach($labels[0] as $ind=>$label){

To:

foreach($labels as $ind => $label) {

Further reading.


Expanding based on your comments:

foreach($labels as $ind => $label) {

    $index = $ind + 2;

    $letter = range('A', 'Z')[$ind2];
    $val = explode('>', $data);

    $objPHPExcel->getActiveSheet()->setCellValue($letter . $index, $val[1]);

}
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement