1
votes

I have array data as shown below, I want to store 'sale' value into database if my currency are USD.

 Array ( [currency] =>  USD [sale] => 9120.00  [buy] => 8970.00  ) 
 Array ( [currency] =>  SGD [sale] => 6653.75  [buy] => 6520.75  ) 
 Array ( [currency] =>  HKD [sale] => 1173.40  [buy] => 1152.10  ) 
 Array ( [currency] =>  CHF [sale] => 8685.40  [buy] => 8517.40  ) 
 Array ( [currency] =>  GBP [sale] => 13958.80  [buy] => 13675.80  ) 
 Array ( [currency] =>  AUD [sale] => 8054.05  [buy] => 7885.05  ) 
 Array ( [currency] =>  JPY [sale] => 105.10  [buy] => 102.40  ) 
 Array ( [currency] =>  SEK [sale] => 1247.90  [buy] => 1216.80  ) 
 Array ( [currency] =>  DKK [sale] => 1590.95  [buy] => 1547.75  ) 
 Array ( [currency] =>  CAD [sale] => 8756.35  [buy] => 8568.35  ) 
 Array ( [currency] =>  EUR [sale] => 11776.75  [buy] => 11555.75  ) 
 Array ( [currency] =>  SAR [sale] => 2441.35  [buy] => 2382.35  ) 
 Array ( [currency] =>  NZD [sale] => 6550.75  [buy] => 6389.75  ) 
 Array ( [currency] =>  CNY [sale] => 1346.75  [buy] => 1322.35  )

Thanks.

Here my code:

foreach ($cur_array as $curs) {
    print_r ($curs)."<br>";
    if ($curs['currency'] = "USD") {
        $curs_sale = $curs['sale'];
            $curs_name = $curs['currency'];
            $db->query("UPDATE currency SET rate = '".
                $curs_sale."' WHERE currency_id ='".$curs_name."'");
    }
}
3
Your table columns don't correspond to your variables. A little confusing there...BoltClock

3 Answers

2
votes

You could just store all the currency arrays in an array, loop through it, check which of the currencies corresponds to USD and save that currency's sale value:

foreach ($currencies as $curr)
{
    if ($curr['currency'] == 'USD')
    {
        // Save $curr['sale'] into your database

        // Break as further iteration isn't needed
        break;
    }
}

In future, please don't mark questions as community wiki if you don't know what community wiki means.

1
votes

What BoltClock proposed is correct. Furthermore, consider altering the structure of your array from:

Array ( [currency] =>  USD [sale] => 9120.00  [buy] => 8970.00  ) 
Array ( [currency] =>  SGD [sale] => 6653.75  [buy] => 6520.75  ) 
Array ( [currency] =>  HKD [sale] => 1173.40  [buy] => 1152.10  ) 
Array ( [currency] =>  CHF [sale] => 8685.40  [buy] => 8517.40  ) 

to:

Array (
    [USD] => Array( [sale] => 9120.00  [buy] => 8970.00 ),
    [SGD] => Array( [sale] => 6653.75  [buy] => 6520.75 ),
    [HKD] => Array( [sale] => 1173.40  [buy] => 1152.10 ),
    [CHF] => Array( [sale] => 8685.40  [buy] => 8517.40 )
)

This structure will allow you to write cleaner code, for example:

$usd_sale = $entries['USD']['sale'];
0
votes

Assuming all the entries are in an array called $entries:

foreach ($entries as $entry) {
    if ($entry['currency'] == 'USD') {
        // do stuff with $entry['sale']
    }
}