Reputation: 25
I want to divide data into multiple users.
<?php
$users = array('13','15','16','16','17','20');
$handle = fopen($_FILES['csvfile']['tmp_name'], 'r');
$i = 1;
while ($data = fgetcsv($handle)) {
foreach ($users as $value) {
echo $data['OrderId'] .":". $value;
$i++;
}
}
?>
output is
Order ID : UserId
405-6219270-3721912 : 13
405-6219270-3721912 : 15
405-6219270-3721912 : 16
405-6219270-3721912 : 17
405-6219270-3721912 : 20
403-5995684-2353914 : 13
403-5995684-2353914 : 15
403-5995684-2353914 : 16
403-5995684-2353914 : 17
403-5995684-2353914 : 20
404-1894735-7034722 : 13
404-1894735-7034722 : 15
404-1894735-7034722 : 16
404-1894735-7034722 : 17
404-1894735-7034722 : 20
406-7756082-9574748 : 13
406-7756082-9574748 : 15
406-7756082-9574748 : 16
406-7756082-9574748 : 17
406-7756082-9574748 : 20
171-7214409-3467567 : 13
171-7214409-3467567 : 15
171-7214409-3467567 : 16
171-7214409-3467567 : 17
171-7214409-3467567 : 20
405-7442385-9605918 : 13
405-7442385-9605918 : 15
405-7442385-9605918 : 16
405-7442385-9605918 : 17
405-7442385-9605918 : 20
But I Want this output
Order ID : UserId
405-6219270-3721912 : 13
403-5995684-2353914 : 15
404-1894735-7034722 : 16
406-7756082-9574748 : 17
171-7214409-3467567 : 20
405-7442385-9605918 : 15
171-7214409-3467569 : 16
171-7214409-3467570 : 17
171-7214409-3467571 : 20
405-7442385-9605972 : 15
405-7442385-9605973 : 16
405-7442385-9605973 : 17
405-7442385-9605974 : 20
Why my loop iteration four-time instead of one?
Upvotes: 0
Views: 48
Reputation: 2705
For each order ID (data), you iterate over all the users. Instead, you could use something like this:
<?php
$users = array('13','15','16','16','17','20');
$handle = fopen($_FILES['csvfile']['tmp_name'], 'r');
// Iterate over the users.
foreach ($users as $user) {
if (($data = fgetcsv($handle)) !== null) {
echo $data['OrderId'] . ':' . $user;
}
}
?>
Iterate over the users, for each user, if there is still csv data, consume that csv data and print order ID and user ID.
Upvotes: 0
Reputation: 57131
Using a nested loop as you do, this will for each order form the file, output each user.
What you can do instead is use 1 loop (reading the input file) and modulus (%
) of the line number ($i
) and output a user per order...
$userCount = count($users);
$i = 0;
while ($data = fgetcsv($handle)) {
echo $data[0] .":". $users[$i % $userCount] . PHP_EOL;
$i++;
}
Upvotes: 1