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)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 linux驱动,linux应用,多线程
  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助