2014-11-24 13 views
0

您好我有這是由下面的代碼生成一個數組結果:如何訪問這個數組

//Get House Sales Date 
// Create a stream 
$username = "test"; 
$password = "test"; 
$remote_url2 = "https://www.streetcheck.co.uk/api/v1/postcode/".$cleanpostcode."/saleprices"; 
$opts2 = array( 'http'=>array( 'method'=>"GET", 'header' => "Authorization: Basic " . base64_encode("$username:$password"))); 
$context2 = stream_context_create($opts2); 

//Open the file using the HTTP headers set above 
$json2 = json_decode(file_get_contents($remote_url2, false, $context2)); 

//If Valid Results Returned 
if($json2->message="ok") 
{ 
    print_r($json2); 

查詢的結果可以看出here

我需要能夠做的是爲每個結果,把值插入到另一個表,到目前爲止我在看是這樣的:

foreach ($json2->result->sales as $item1) 
{ 
    $pricepaid = $json2->result->sales->pricePaidGBP; 
    $propertytype = $json2->result->sales->propertyType; 
    $holding = $json2->result->sales->holding; 
    $nameornumber = $json2->result->sales->nameOrNumber; 
    $fulllocation = $json2->result->sales->fullLocation; 
    $dateoftransfer = $json2->result->sales->dateOfTransfer; 

但結果回來爲空,我在做什麼錯了,請>

+1

可能想'$ pricepade = $ item1-> pricePaidGBP'。否則爲什麼麻煩循環「 - > result-> sales」,然後完全忽略循環爲您生成的變量? – 2014-11-24 16:55:18

回答

1

轉換成數組 -

$json2 = json_decode(file_get_contents($remote_url2, false, $context2), true); 

然後你可以檢索像這樣對每個項目 -

foreach ($json2 as $item) 
    { 
    $pricepaid = $item['result']['sales']['pricePaidGBP']; 
    // ... the rest of the items 
+0

這是一個對象http://prntscr.com/59okbm。 – 2014-11-24 16:54:24

+0

它看起來像一個對象內的數組 – Simon79 2014-11-24 16:55:09

+0

郵政編輯,但它仍然是一個數組陣列,你必須做一個'for'循環。 – 2014-11-24 16:58:21

1

你試試這個:

foreach ($json2->result->sales as $item) { 
    $pricepaid = $item->pricePaidGBP; 
    $propertytype = $item->propertyType; 
    $holding = $item->holding; 
    $nameornumber = $item->nameOrNumber; 
    $fulllocation = $item->fullLocation; 
    $dateoftransfer = $item->dateOfTransfer; 
    ... 
} 
+0

謝謝你做到了! – Simon79 2014-11-24 16:57:55