Reputation: 6820
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>";
}
?>
Upvotes: 0
Views: 2144
Reputation: 3845
In the above code snippet you need to create multidimensional array using array_push function.
Eg array_push($arr['exchange'],array('to' => $to, 'rate' => $result[0]));
Upvotes: 0
Reputation: 4419
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.
$currencies = array("USD", "NZD", "KWD", "GBP", "AUD");
$cross = array();
foreach ($currencies as $from) {
$cross[$from] = 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);
//echo "$from:$to - <br/>";
//var_dump($result);
fclose($handle);
$cross[$from][$to] = $result[0];
}
} else {
$cross[$from][$to] = 1;
}
}
print json_encode($cross);
print"<br><br>";
}
This way you'll end up with something like this:
{
"USD": {...},
"NZD": {"USD":1.532,"NZD":1,"KWD":0.81,"GBP":1.546,"AUD":1.120},
"KWD": {...},
"GBP": {...},
"AUD": {...}
}
And can access it in javascript like:
cross[from][to]
or
cross.NZD.USD
Upvotes: 1
Reputation: 8298
When adding additional indexes to an array in PHP, you can use the square brackets[].
For example, $arr['exchange'][] = array('to' => $to, 'rate' => $result[0]);
Upvotes: 2