1

I have the following code which I am trying to compare a title in a csv file & pull back the appropriate price (in the csv) depending on the title:

<a class="Title" href="<?php echo $item->link;?>">
   <?php echo $item->title;?> <!--country title-->
</a>
<?php
       $pricelist = array();
       if (($handle = fopen("townprices.csv", "r")) !== FALSE)
       {
          while (($data = fgetcsv($handle, 1000, ",")) !== FALSE)
          {
             $pricelist[] = $data;
          }
          fclose($handle);
       }
       echo '<pre>'; print_r($pricelist); echo '</pre>';
?>

CSV contents:

Spain, 250
France, 350
Germany, 150

(town/title, price)

This bring back the following array from my csv:

Array
(
    [0] => Array
        (
            [0] => Spain
            [1] =>  250
        )
    [1] => Array
        (
            [0] => France
            [1] =>  350
        )
    [2] => Array
        (
            [0] => Germany
            [1] =>  150
        )
)

What I now need to do is just echo the right price, rather than

echo '<pre>'; print_r($pricelist); echo '</pre>';

So I need to create an if statement, something like:

if $item->title = Spain, print 250

But I am stuck on how to do this. Any help would be appreciated. Thanks

1
  • foreach ($pricelist as $value) { ... }? Commented Jan 20, 2012 at 10:03

2 Answers 2

2

I think you should index your CSV.

Let me give you an example.

$pricelist = array();
if (($handle = fopen("townprices.csv", "r")) !== FALSE) {
  while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
    $pricelist[$data[0]] = $data[1];
  }
  fclose($handle);
}

So

echo $pricelist['Spain']; // Would give 250
Sign up to request clarification or add additional context in comments.

3 Comments

an example would be great... I'm stuck on passing this array as a variable into my view... so if title = Spain - echo 250
brillaint... so can I do this to match the country in the csv <?php echo $pricelist['$item->title']; ?>
Yes without the quotes around $item->title like <?php echo $pricelist[$item->title] ?>. Not tested but should work
1

To list all prices, just do this:

foreach ($pricelist as $line) {
    echo $line[0].": &euro; ".$line[1]."<br />";
}

To find the price for a certain country, do this:

foreach ($pricelist as $line) {
    if($line[0] == "Spain") echo $line[1];
}

This will get slow on large source files though.

Comments

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.