Jump to content

Issue with passing Array Data from Loop1 to Loop2


Go to solution Solved by Danishhafeez,

Recommended Posts

I'm trying to add data to a CSV file with dynamic variable data but getting stuck on the 2nd loop which retrieves the data which gets the error Uncaught TypeError: Illegal offset type

Dynamic Variables:
Loop 1: $value which contains column names for the data e.g. SKU, Price, Quantity..

Loop 2: $row2 which contains data for the above columns

Loop 1 Column Names:

$column_names_array[] =$value;
// Array ( [0] => SKU [1] => Price [2] => Quantity ) 
// This is dynamic array so variables above can vary

Loop2: Data for the column names

$data_array = array($row2[$column_names_array]);
// This wont work as $column_names_array from Loop1 is already in its own array 
// Looking for a way to add $row2 to $column_names_array and combine into an array such as:
// $data_array = array($row2['SKU'], $row2['Quantity'], $row2['sell_price']); 
// but this needs to be dynamic such as $data_array = array($row2[$column_names_array]);

 

Code:

fputcsv($csvfile, $export_column_name_array, $delimiter); 

$stmt2 = $conn->prepare($sql_built_statement);
//$stmt2->bind_param("ii", $company_id, $company_id);	WILL ADD THIS LATER ONCE WORKING 				
$stmt2->execute();
$result2 = $stmt2->get_result();
	if($result2 != NULL){
		// Add column names to array 
		foreach ($export_column_name_array as $value) {																			
			$column_names_array[] =$value;
		} 
		//print_r($column_names_array);
		//Array ( [0] => SKU [1] => Price [2] => Quantity ) 
		
		// Retrieve data for each column 
		while($row2=$result2->fetch_assoc()){
			// MANUALLY SETTING VARIABLES WORKS e.g.: 
			// $data_array = array($row2['SKU'], $row2['Quantity'], $row2['sell_price']);	
			// print_r($data_array);	
			// Array ( [0] => ABC123 [1] => 99 [2] => 123.00 )	
			$data_array = array($row2[$column_names_array]);	// Uncaught TypeError: Illegal offset type					
		}
		//print_r ($data_array); 
		fputcsv($csvfile, $data_array, $delimiter);						
	}																
	fclose($csvfile);

 

I have tried combining the 2 loops which semi works, however the data replicates into each array on each loop such as:

Quote

Array ( [0] => ABC123 [1] => 10860 [2] => 10 )
Array ( [0] => ABC123 [1] => 10860 [2] => 10 [3] => DEFGHI [4] => 20860 [5] => 10 )
Array ( [0] => ABC123 [1] => 10860 [2] => 10 [3] => DEFGHI [4] => 20860 [5] => 10 [6] => JLKMNO [7] => 396.63 [8] => 10 ) 

 

Code:

fputcsv($csvfile, $export_column_name_array, $delimiter); 

$stmt2 = $conn->prepare($sql_built_statement);
//$stmt2->bind_param("ii", $company_id, $company_id);	WILL ADD THIS LATER ONCE WORKING 				
$stmt2->execute();
$result2 = $stmt2->get_result();
	if($result2 != NULL){			
		// Retrieve data 
		while($row2=$result2->fetch_assoc()){
			// Add column names and data to array 
			foreach ($export_column_name_array as $value) {																			
			$column_names_array[] =$row2[$value];
			} 
		//print_r($column_names_array);					
		}
		fputcsv($csvfile, $column_names_array, $delimiter);						
	}																
	fclose($csvfile);

 

Edited by experience40
Link to comment
Share on other sites

where are you getting $value from and how are you building the SELECT ... list in the data query? if they are in the same order, you don't need to do anything else, the rows of fetched data will match the csv columns/headings in $value.

Link to comment
Share on other sites

  • Solution

It seems like you're trying to dynamically retrieve column names from the first loop and then use them to fetch corresponding data from the database in the second loop. However, you're facing issues with the data retrieval part. Let's correct the code:

fputcsv($csvfile, $export_column_name_array, $delimiter); 

$stmt2 = $conn->prepare($sql_built_statement);
//$stmt2->bind_param("ii", $company_id, $company_id);	WILL ADD THIS LATER ONCE WORKING 				
$stmt2->execute();
$result2 = $stmt2->get_result();
if($result2 != NULL){			
    // Retrieve data 
    while($row2=$result2->fetch_assoc()){
        // Initialize an empty data array for each row
        $data_array = array();
        // Add data for each column
        foreach ($export_column_name_array as $value) {																			
            // Push data for each column into the data array
            $data_array[] = $row2[$value];
        } 
        // Write the data array to the CSV file
        fputcsv($csvfile, $data_array, $delimiter);					
    }
}																
fclose($csvfile);

In this corrected code:

We loop through each row of the fetched data and initialize an empty $data_array for each row.

Within the row loop, we iterate through each column name from $export_column_name_array.

For each column name, we fetch the corresponding data from the $row2 associative array and add it to the $data_array.

After populating the $data_array with data for all columns, we write it to the CSV file using fputcsv().

The process repeats for each row fetched from the database until all rows have been processed.

i hope This should correctly populate your CSV file with the data fetched from the database, using the dynamic column names obtained from $export_column_name_array.

Best Regard

Danish hafeez | QA Assistant

ICTInnovations

  • Thanks 1
Link to comment
Share on other sites

4 hours ago, Danishhafeez said:
// Initialize an empty data array for each row
        $data_array = array();

Ah the pennies dropped 🙂

I didnt realise array() initialized a new empty array, i thought $data_array[] was enough to create an array but i guess the [] adds items to the array rather than creating a new one on each loop 

Many thanks Danish, you've saved me ALOT of hair pulling on why i couldnt get this to work

Superb, much appreciated!

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.