2013-05-09 74 views
1

這可能是一個簡單的問題,但是如何將如下所示的變量放入數組中。如何使數組格式的變量變成數組

$hot = "It","is","hot","outside"; 

執行下列操作不起作用:

$newhot = array($hot); 

我實際調用看起來的API,如:

[["P0010001","NAME","state","zip code tabulation area"], 
    ["68191","ZCTA5 99301","53","99301"]] 

我需要的是在第二線的人口(第一引號)。

執行以下操作,給了我 「68191」, 「ZCTA5 99301」, 「53」, 「99301」

$splitContent = implode("\n",array_slice(explode("\n",$populate),1,2)); 
    $newContent = str_replace(']','',$splitContent); 
    $newContent = str_replace('[','',$newContent); 
+0

看起來像一個語法錯誤。 – elclanrs 2013-05-09 23:31:40

+1

$ hot =「It」,「is」,「hot」,「outside」;不是變量 – 2013-05-09 23:31:59

+2

'json_decode($ populate);'? – 2013-05-09 23:32:43

回答

3

$hot = "It","is","hot","outside"; 

將在PHP中生成錯誤。但是,假設你有以下從API檢索:

$str='[["P0010001","NAME","state","zip code tabulation area"],["68191","ZCTA5 99301","53","99301"]]'; 

那麼,如果你跑這條線:

$myArray = json_decode($str); 

然後

echo "<pre>"; 
print_r($myArray); 
echo"</pre>"; 

你可以有這樣的結果:

Array 
(
    [0] => Array 
     (
      [0] => P0010001 
      [1] => NAME 
      [2] => state 
      [3] => zip code tabulation area 
     ) 

    [1] => Array 
     (
      [0] => 68191 
      [1] => ZCTA5 99301 
      [2] => 53 
      [3] => 99301 
     ) 

) 

第二行數據將被存儲在

$myArray[1] 
2

定義的數組是一樣的東西......

$hot = array("It","is","hot","outside"); 

回覆:你的API調用...

$ApiResponse = '[["P0010001","NAME","state","zip code tabulation area"],["68191","ZCTA5 99301","53","99301"]]'; 

$Response = json_decode($ApiResponse); 
$Data = $Response[1]; 

具體來說,該API將返回一個列表的列表。我們正在採用第二個(0索引)列表。 $Data現在是一樣的,如果你宣佈...

$Data = array("68191","ZCTA5 99301","53","99301"); 

編輯:測試的代碼...

$Key = '[Your Key]'; 
$ApiResponse = file_get_contents("http://api.census.gov/data/2010/sf1?key={$Key}&get=P0010001,NAME&for=zip+code+tabulation+area:99301&in=state:53"); 

print "Raw: " . print_r($ApiResponse, true) . "<hr/>"; 

$Response = json_decode($ApiResponse); 
$Data = $Response[1]; 
print "Extracted Data: " . print_r($Data, true) . "<br/>"; 

print "First bit of data: {$Data[0]}.<br/>"; 
print "Second bit of data: {$Data[1]}.<br/>"; 
+0

我不能做第一個。結果已經在一個變量中。我需要將變量中的結果轉換爲數組。 – Jeight 2013-05-09 23:43:13

+0

您的第一個(已編輯的)代碼段中的語法無效。如果_all_結果在變量中,它可以是一個數組(問題已解決),也可以是json數組的字符串表示形式 - 在這種情況下,請使用'json_decode'。有沒有這樣的事情多個值不是一個數組(或對象/列表/等) – Basic 2013-05-09 23:46:10

+0

$ populate = file_get_contents('http:// apisite。COM「); $ NewContent = json_decode($ populate)[1]; echo $ NewContent [1]; - 不起作用..得到服務器錯誤。我不確定我在做什麼不正確。 – Jeight 2013-05-09 23:55:02