在JavaScript中,如果我有来自JSON的对象或数组
var arr = ["one", "two", "three"];
var obj = {"hello": "dolly", "jurassic": "park"}
我可以轻松地从中获取任何单个项目而无需循环:
alert(arr[1]); // outputs "two"
alert(obj["hello"]); // outputs "dolly"
在PHP中有类似的方法吗?
echo arr[1];
echo obj["hello"];
echo arr->1
echo obj->"hello"
答案 0 :(得分:3)
在PHP中,它完全相同。
<强>的Javascript 强>
var foo = ['bar', 'baz', 'quux'];
console.log(foo[1]);
var q = { key: 'value', otherkey: 'othervalue' };
console.log(q['value']);
<强> PHP 强>
$foo = array('bar', 'baz', 'quux');
echo $foo[1]; // prints "baz"
$q = array('key' => 'value', 'otherkey' => 'othervalue');
echo $q['key']; // prints 'value'
答案 1 :(得分:3)
这应该是相当明确的解释:
php > $arr = json_decode('["one","two","three"]');
php > echo $arr[2];
three
php > $obj = (array) json_decode('{"hello":"dolly","jurassic":"park"}');
php > echo $obj["hello"];
dolly
php > $obj = json_decode('{"hello":"dolly","jurassic":"park"}');
php > echo $obj->hello;
dolly
答案 2 :(得分:2)
在php中:
$arr = array("one", "two", "three");
$obj = array("hello" => "dolly", "jurassic" => "park");
echo $arr[1];// print two
echo $obj["hello"]; // print dolly
请记住,数组从索引零开始