如何将数组格式的变量转换为数组

时间:2013-05-09 23:29:52

标签: php arrays api variables

这可能是一个简单的问题,但我如何获取如下变量并将其变为数组。

    $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);

2 个答案:

答案 0 :(得分: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]

答案 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/>";
相关问题