0

I have a CSV file containing multiple columns, I would like to sort and filter like I do with SQL.

CSV structure -

Type  |  Vin  | DateInStock
New   |  675F |   12/06/19
Used  |  7643 |   12/05/19

etc..

Here is my PHP file -

$fh = fopen('myFile.csv', 'r');
while($line = fgetcsv($fh)) {
    $type[] = array($line[0]); 
    $vin[] = array($line[1]); 
    $date[] = array($line[2]); 
}

So What I would normally do is

"SELECT * FROM table WHERE type = 'Used' AND date = '$todays_date'";

Then echo out all the Vin numbers

$vin = $row['vin'];

I can get an array of the type, vin and date but not sure how to just display vin's that are from todays date and have a type of Used. What would I do to accomplish this? I tried this for just getting vin numbers with the type Used -

  foreach($type as $t){
      $recall_type = $t[0];
      if($recall_type == 'Used'){
          foreach ( $vin as $value ){
              $recall_vin = $value[0];    
              $recall_vin.'<br>';
          } 
      } 
   }

But that just echos out the same vin pattern hundreds of times..

1 Answer 1

2

I would read all the values into a single multidimensional array; then you can filter that using array_filter based on the criteria you have. For example:

$fh       = fopen('myFile.csv', 'r');
$vehicles = array();
while($line = fgetcsv($fh)) {
    $vehicles[] = array(
                        'type' => $line[0], 
                        'vin'  => $line[1], 
                        'date' => $line[2]
                        );
}
// get today's date in a format to match the CSV
$today = date('m/d/y');
$vehicles = array_filter($vehicles, function ($v) use ($today) { 
    return $v['type'] == 'Used' && $v['date'] == $today;
});

Demo on 3v4l.org

Sign up to request clarification or add additional context in comments.

6 Comments

Thank you, Where is $v being declared? Im a little confused.. Im not to familiar with multidimensional arrays
@RyanD $v is a dummy variable which represents the current value of the array as array_filter iterates through it.
Ok cool, It returns a blank page, when I print out $vehicles the multidimensional array is correct and has the the correct values. Do I need to do something with the return value? sorry for being a noob..
@RyanD see my edit, I've added a link to a demo; as you can see $vehicles has only the matching vehicle after the call to array_filter
It has to do with return $v['type'] == 'Used' && $v['date'] == $today; If I remove && == $today I get the results in an array. I checked the date format and they are the correct format
|

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.