sub array in array PHP -
ok issue strange. when following
$arr['exchange'] = array('to' => $to, 'rate' => $result[0]); the code works prints once
when this
$arr['exchange'] .= array('to' => $to, 'rate' => $result[0]); it prints out
{"from":"nzd","exchange":"arrayarrayarrayarray"} so please , tell me correct way loop though can set 6 sub array in exchange array
here full code
<?php $currencies = array("usd", "nzd", "kwd", "gbp", "aud"); foreach ($currencies $from) { $arr = array(); $arr['from'] = $from; //$arr['exchange'] = array(); foreach ($currencies $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 few issues code, namely looking [] notation append array.
secondly, understand you're trying array formation i'm not sure why. seems easier create array shown below using keys keep track of various exchange rate crosses, easier manage on javascript side of things later.
$currencies = array("usd", "nzd", "kwd", "gbp", "aud"); $cross = array(); foreach ($currencies $from) { $cross[$from] = array(); foreach ($currencies $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 this:
{ "usd": {...}, "nzd": {"usd":1.532,"nzd":1,"kwd":0.81,"gbp":1.546,"aud":1.120}, "kwd": {...}, "gbp": {...}, "aud": {...} } and can access in javascript like:
cross[from][to]
or
cross.nzd.usd
Comments
Post a Comment