使用php访问哈希元素

时间:2012-07-18 06:18:12

标签: php arrays hash

我有一个表格

的哈希数组
[{"sector":"Consumer, Cyclical","ticker":"NWY","entity":"New York & Co","New_York_&_Co":[{"count":1,"entity":"New York"}],"type":"SCap"}]

我正在尝试列出与所有出现的键值“entity”对应的值。 我确实使用了json_decode,

$testJson = json_decode('[{"sector":"Consumer, Cyclical","ticker":"NWY","entity":"New York & Co","New_York_&_Co":[{"count":1,"entity":"New York"}],"type":"SCap"}]');

当我尝试`echo var_dump($ testJson [0]);
它以表格

显示输出
array
  0 => 
  object(stdClass)[438]
  public 'sector' => string 'Consumer, Cyclical' (length=18)
  public 'ticker' => string 'NWY' (length=3)
  public 'entity' => string 'New York & Co' (length=13)
  public 'New_York_&_Co' => 
    array
      0 => 
        object(stdClass)[439]
          ...
  public 'type' => string 'SCap' (length=4)

echo var_dump($testJson[0]->entity)或echo var_dump($ testJson [0] - > sector)给了我错误..“试图获取非对象的属性”..我可能做错了什么?

1 个答案:

答案 0 :(得分:1)

$testJSon= json_decode('[{"sector":"Consumer, Cyclical","ticker":"NWY","entity":"New York & Co","New_York_&_Co":[{"count":1,"entity":"New York"}],"type":"SCap"}]');
//var_dump($testJSon);
echo $testJSon['0']->sector; // will output `Consumer, Cyclical`
echo $testJSon[0]->{'sector'}; // will also output same

你可以在数组中转换它并获得如下值:

$testJSon= json_decode('[{"sector":"Consumer, Cyclical","ticker":"NWY","entity":"New York & Co","New_York_&_Co":[{"count":1,"entity":"New York"}],"type":"SCap"}]',true);
echo $testJSon[0]['entity']; // will return "New York & Co"