首先,对不起,因为我的英语不好。
我遇到了一个问题。从 JSON 格式的 URL 请求数据,得到如下内容:
array(1) { ["NICK_HERE"]=> array(5) { ["id"]=> int(123456789) ["name"]=> string(11) "NICK_HERE" ["class"]=> int(538) ["level"]=> int(97) ["online"]=> int(1420061059000) } }
然后,我想从那里显示一些东西,通常它会是$x['NICK_HERE']['id']
,但是因为NICK_HERE
会发生变化,并且因为我不能在其中使用变量,有没有办法绕过它?例如,像$x[0]['id']
?先选择一下,不管怎么样?
感谢您的帮助!
附言新年快乐!
我的建议(因为我认为最简单的是使用current()
,但您也可以使用array_column()
...
代码:(演示)
$array=[
"NICK_HERE"=>["id"=>123456789,"name"=>"NICK_HERE","class"=>538,"level"=>97,"online"=>1420061059000]
];
echo current($array)['id'];
echo "'n";
echo array_column($array,'id')[0];
输出:
123456789
123456789
这些方法假定子数组元素id
保证存在。 如果可能不是,您需要在尝试访问之前与isset()
核实 - 以避免通知。
由于您知道第一个数组有一个键名,因此您可以获得第 0 个键。
测试.php
$x = array(
"NICK_HERE" => array(
"id" => 123456789,
"name" => "NICK_HERE",
"class" => 538,
"level" => 97,
"online" => 1420061059000
)
);
$name = array_keys($x)[0];
echo $x[$name]["id"];
?>
输出:
php test.php
123456789%
使用 foreach 循环。
假设您的数组名称为 $array。
foreach($array as $i=>$a)
{
echo "index: ".$i." id:".$a['id']."<br>";
}
假设您的 json 字符串名称为 $json
。然后使用这种方式
$array=$json_decode($json);
foreach($array as $i=>$a)
{
echo "index: ".$i." id:".$a->id."<br>";//here you will get it as object
}
希望你明白了。