按键引用PHP子数组


Reference PHP Sub-Arrays by Key

我正在使用PHP 5.4处理从HTTP API返回的一些数据。数据以XML格式返回,然后使用以下命令将其转换为数组:

$xml = simplexml_load_string($resp);
$json = json_encode($xml);
$arr = json_decode($json, true);

这给了我数组形式的数据(如果有更好的方法做到这一点,请告诉我!)。结果是下面的示例数组:

array (
  '@attributes' =>
  array (
    'status' => 'success',
    'code' => '19',
  ),
  'result' =>
  array (
    '@attributes' =>
    array (
      'total-count' => '1',
      'count' => '1',
    ),
    'user' =>
    array (
      'entry' =>
      array (
        0 =>
        array (
          '@attributes' =>
          array (
            'name' => 'chris',
          ),
          'phash' => 's98djf384jr0oq8jf8j3948jfw',
        ),
        1 =>
        array (
          '@attributes' =>
          array (
            'name' => 'test',
          ),
          'phash' => '9a8sdfu9n2308ja8fj34ojr9a0',
        ),
      ),
    ),
  ),
)

我想弄清楚的是如何正确引用数组的各种元素。我已经尝试通过索引引用,如echo $arr[0][0],但这没有返回任何东西,我找不到如何通过键引用子数组。

这在PHP手册中有明确的记录。

http://www.php.net/manual/en/language.types.array.php

PHP中的

数组是键/值对。当没有指定键时,PHP将使用数字索引。

您可以访问这些值为$arr['@attributes']['status']

检查键是否存在,可以使用isset($arr['@attributes'])array_key_exists('@attributes',$arr)

枚举

foreach($arr as $key=>$value) { .... }
http://ca1.php.net/manual/en/control-structures.foreach.php