douzui6173 2016-11-09 06:16
浏览 19
已采纳

因为基本的错误,我把头发拉了出来

I think i'm to old or i'm just stupid but i can't understand why i can't loop on an simple array.

I have this code:

$results = [];
for ($i = 0; $i < count($links); $i++) {
   $results[] = [
      'site' => $links[$i],
      'pda'  => $data[$i]->pda
   ];
}

The $links array contains a list of urls and $data contains a list of values like this:

array(3) {
  0 =>  object(stdClass) 
    {
      "pda" => int 100
    }
  1 =>  object(stdClass) 
    {
      "pda" => int 100
    }
  2 =>  object(stdClass) 
    {
      "pda" => int 1
    }
}

EDIT: This is the print_r($data) content...it seems that some of you don't understand the dump from above and prefer the print_r solution :-|

Array
(
    [0] => stdClass Object
        (
            [pda] => 100
        )

    [1] => stdClass Object
        (
            [pda] => 1
        )

    [2] => stdClass Object
        (
            [pda] => 100
        )

)

If i do $data[$i]->pda in the loop i get "Cannot use object of type stdClass as array" error.

If i try to access it as an object, i get "Trying to get property of non-object" error.

Bottom line, am i stupid or i'm going crazy?!

Thank you!

  • 写回答

2条回答 默认 最新

  • dtnbjjq51949 2016-11-09 07:35
    关注

    Little bit extended answer from comments:

    You probably have a different number of $links than $data. Debug with a simple if else condition before accessing $data[$i] and dump the actual result if it fails.

    for ($i = 0; $i < count($links); $i++) {
      if (isset($data[$i])) {
          $results[] = [
           'site' => $links[$i],
           'pda'  => $data[$i]->pda
        ];
      } else {
        // Somethings wrong
        var_dump($i);
        var_dump($links);
        var_dump($data);
      }
    
    }
    

    So if your function gets called several times, you are dumping the actual data when the error happens.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大