1

This is probably a simple question, but how do I take a variable like the following and make it into an array.

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

Doing the following doesn't work:

    $newhot = array($hot);

I'm actually calling an API that looks like:

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

What I need is the population on the second line (first quotes).

Doing the following gives me "68191","ZCTA5 99301","53","99301"

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

2 回答 2

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]
于 2013-05-10T00:14:09.887 回答
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/>";
于 2013-05-09T23:34:36.253 回答