Reputation: 472
I am trying to creat an CSV file for each array(111, arm_2, trye) inside the $StockReady array.
$StockReady
Array
(
[111] => Array()
[arm_2] => Array()
[trye] => Array()
)
I have this:
$CurrentArmazem = $StockReady;
reset($CurrentArmazem);
$CurrentArmazem = key($CurrentArmazem);
foreach ($StockReady as $CodArmazem => $line) {
$FileName = $CodArmazem . '.csv';
if ($CurrentArmazem === $CodArmazem) {
foreach ($line as $value) {
$Stocks .= $value[0];
}
$doc = $dir . $FileName;
$myfile = fopen($doc, "w");
fwrite($myfile, $Stocks . "\n");
fclose($myfile);
}else{
$CurrentArmazem = $CodArmazem;
}
}
So this runs good for the first time because $currentarmazem is set 'manually' but when it goes to the next array it wont work because if ($CurrentArmazem === $CodArmazem)
is not true anymore, it instead incorrectly goes into the else
and does not re-run that array. Is there anything I can put inside the else
so it returns to the array it missed?
Upvotes: 1
Views: 59
Reputation: 8338
foreach ($StockReady as $CodArmazem => $line) {
$FileName = $CodArmazem . '.csv';
foreach ($line as $value) {
$Stocks = $value[0];
}
$doc = $dir . $FileName;
$myfile = fopen($doc, "w");
fwrite($myfile, $Stocks . "\n");
fclose($myfile);
}
You can simple remove your if/else statement and have it work. You will create the file based on your key
value because you assign a value to your $FileName
variable based on your array key, in every loop.
Edited my code based on your comment so your $Stocks
variable will be reassigned with a new value for every loop.
Based on your code you were concatenating data to the same variable so you ended up with all the data from all the arrays to be stored in this variable cause of wrong concatenation.
Upvotes: 2
Reputation: 1872
Explanation:
It doesn't actually look like you need the if/else, the key will change on each loop, I'm also not sure why you're resetting the array when nothing has been changed.
In addition to this, I am now resetting the $Stocks variable on each iteration, so the following loop should not contain any of the previous loops data.
Try replacing your code with the below:
foreach ($StockReady as $CodArmazem => $line) {
$Stocks = '';
$FileName = $CodArmazem . '.csv';
foreach ($line as $value) $Stocks .= $value[0];
$doc = $dir . $FileName;
$myfile = fopen($doc, "w");
fwrite($myfile, $Stocks . "\n");
fclose($myfile);
}
Upvotes: 1