0

I have a csv like this.

enter image description here

I have created a CLI script, which will read the CSV and It will create an array based on account id, address id and SKU.

I will execute the script like this

    php csvimport.php 10 /var/www/test/testcsv.csv

In the above code, 10 is the limit of the script which will take the first 10 then it will create an array, then it will look for next 10 and it will create another array. Here I need to handle a condition that the first row value of the batch should match the next 9 rows. If there is no match after the first row then will create that row as separate array.

I need the expected output. Every time it will take the limit and compare the rows based on the first row of the limit.

array[A1][ad1] => SKU1,SKU2,SKU3,SKU4,SKU5,SKU25,SKU26
array[A1][ad12] => SKU1
array[A1][ad2] =>  SKU3,SKU4,SKU5,SKU6,SKU7,SKU8
array[A2][ad2-1] =>  SKU13,SKU14,SKU15,SKU16,SKU17,SKU18
$file = '/var/www/html/var/csv/cv1.csv';
$arr=array();
$row = 1;
$i = 1;
$limit = 10;
if (($handle = fopen($file, "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $num = count($data);
        $row++;
        for ($c = 0; $c < $num; $c++) {
            $arr[$row][$data[0]][$data[1]]= $data[$c];
            if ($i++ == $limit) break;
        }
    }
    fclose($handle);
}

echo "<pre>";
print_r($arr);
exit;
4
  • 1
    Any code that you have tried? Commented Jun 19, 2018 at 4:28
  • What's code you have tried in "csvimport.php"? Commented Jun 19, 2018 at 4:45
  • @LovepreetSingh updated my code Commented Jun 19, 2018 at 6:35
  • currently it was coming like this [1] => Array ( [A1] => Array ( [ad1] => SKU1 ) ) [2] => Array ( [A1] => Array ( [ad1] => SKU2 ) ) Commented Jun 19, 2018 at 6:36

1 Answer 1

1

There is need to update code inside for loop. Update it as:

for ($c = 0; $c < $num; $c++) {
    if (isset($arr[$data[0]]) && isset($arr[$data[0]][$data[1]])) {
        $arr[$data[0]][$data[1]] .= "," . $data[$num - 1];
    } else {
        $arr[$data[0]][$data[1]] = $data[$num - 1];
    }
    if ($i++ == $limit)
        break;
}
Sign up to request clarification or add additional context in comments.

2 Comments

The array is coming like this, It's taking the account id & address id instead of taking only SKU[A1] => Array ( [ad1] => Array ( [0] => A1 [1] => ad1 [2] => SKU1 [3] => A1 [4] => ad1 [5] => SKU2 [6] => A1 [7] => A1 [8] => ad1 [9] => SKU4 )
Looks better but the result now it's coming as array[A1][ad1] => A1,ad1,SKU1,A1,ad1,SKU2,A1,A1,ad1,SKU4,A1,ad1,SKU5,A1,ad1,SKU25,A1,ad1,SKU26 expected array[A1][ad1] => SKU1,SKU2,SKU3,SKU4,SKU5,SKU25,SKU26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.