dousuize3082 2015-02-20 01:24
浏览 24
已采纳

数组内部的索引无法正常工作

I seem to be unable to access an array inside an array with index.

this

var_dump($graphed[0]);

give me this

array (size=2)
  'date' => string '02-03-15' (length=8)
  'weight' => string '82.327015155' (length=12)

this

var_dump($graphed[0]['weight']);

gives me this

 string '82.327015155' (length=12)

BUT this

var_dump($graphed[0][1]);

gives me THIS

A PHP Error was encountered

Severity: Notice

Message: Undefined offset: 1

Filename: progress/compare.php

Line Number: 17

null

I have no idea where to go from here. Everything I know about PHP tells me this shouldn't be happening.

By the way, this

echo phpversion();

gives me

 5.5.12

Am I crazy? What's going on?

  • 写回答

1条回答 默认 最新

  • dongwh1992 2015-02-20 01:32
    关注

    PHP makes a clear destinction between associative elements (with a key) and indexed elements (with an index). You can't access an element with a key in such way. In other words: they are not interleaved. PHP sees an array as a composition of an Array(List) (like you known them in Java) and a HashMap. The difference with Java is that the keys are furthermore guaranteed to be ordered. But that doesn't mean the keys themselve correspond to an index. In a HashMap<T> you neither can get the i-th value.

    Example:

    php > var_dump(array(1,2,3,'foo'=>'bar',7));
    array(5) {
      [0]=>
      int(1)
      [1]=>
      int(2)
      [2]=>
      int(3)
      ["foo"]=>
      string(3) "bar"
      [3]=>
      int(7)
    }
    

    In other words, "foo" doesn't map on an index, the index numbering only considers indexed elements. For the indexer, it's as if "foo" => "bar" doesn't exist.

    You can however obtain the list of keys - which is an indexed array - and then pick that key as is written here:

    $keys = array_keys($graphed[0]);
    echo $graphed[0][$keys[1]];
    

    PHP guarantees key ordering so it's safe to do so (given you know of course the order in advance, or know what you are doing).

    Note that the keys include the indices:

    php > var_dump(array_keys(array(1,2,3,'foo'=>'bar',7)));
    array(5) {
      [0]=>
      int(0)
      [1]=>
      int(1)
      [2]=>
      int(2)
      [3]=>
      string(3) "foo"
      [4]=>
      int(3)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路