PHP Extract only simple products with price below 10 from a csv file

I am trying to get some specific data from a csv file. Here is the link of the file:

Here is my code:

     <?php
     $row = 1;
     $mycsvfile = array(); //define the main array.
     $new_array = array();
     if (($handle = fopen("php-files-task.csv", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {

    if($data['product_type'] == 'simple' && $data['price'] < 10){
    $new_array = array_push($new_array, $data);
   }
   }
   fclose($handle);
   $fp = ['sku', 'product_type', 'name', 'price'];
   foreach ($new_array as $key => $value) {
   fputcsv($fp, $value);
   }
   }
  ?>

When I execute the code I get undefined index: ‘product type’. Also I am wondering how to put the result of $value in a new file called , results.csv". Thanks in advance

You are referencing a key that doesn’t exist.

However, now I have warnings regarding array_push()- expects parameter 1 to be array, integer and null given in this line: $new_array = array_push($new_array, $data); Actually the array is always empty.

Just read the manual really carefully:

Return Values
Returns the new number of elements in the array.

https://www.php.net/manual/en/function.array-push.php

so what is $new_array after your line of code? Check with var_dump()

Sponsor our Newsletter | Privacy Policy | Terms of Service