When I do the following
$arr['exchange'] = array('to' => $to, 'rate' => $result[0]);
the code works however only prints once.
When I do this
$arr['exchange'] .= array('to' => $to, 'rate' => $result[0]);
it prints out
{"from":"NZD","exchange":"ArrayArrayArrayArray"}
What is the correct way to loop though so that it can set 6 sub array in the exchange array?
Here is my full code
<?php
$currencies = array("USD", "NZD", "KWD", "GBP", "AUD");
foreach ($currencies as $from)
{
$arr = array();
$arr['from'] = $from;
//$arr['exchange'] = array();
foreach ($currencies as $to)
{
if($from != $to)
{
$url = 'http://finance.yahoo.com/d/quotes.csv?f=l1d1t1&s='.$from.$to.'=X';
$handle = fopen($url, 'r');
if ($handle) {
$result = fgetcsv($handle);
fclose($handle);
}
$results = $result[1].$result[2];
$arr['exchange'] = array('to' => $to, 'rate' => $result[0]);
}
}
print json_encode($arr);
print"<br><br>";
}
?>
There are a few issues with your code, namely you are looking for the
[]notation to append into an array.Secondly, I understand what you’re trying to do with that array formation but I’m not really sure why. It seems like it would be easier to create an array like shown below using the keys to keep track of the various exchange rate crosses, this will also be easier to manage on the javascript side of things later.
This way you’ll end up with something like this:
And can access it in javascript like:
cross[from][to]or
cross.NZD.USD