PHP:未定义的偏移量:0,但不是dd()

时间:2017-10-10 22:06:12

标签: php laravel laravel-5

我在laravel中遇到Undefined offset: 0错误。奇怪的是,当我dd()时,它会出现。

  $ports = $container->getPorts();
  $ports = $ports[0];

这会返回Undefined offset: 0

当我dd()

$ports = $container->getPorts();
dd($ports[0]);

Port {#336 
  #privatePort: 80
  #publicPort: 32780
  #type: "tcp"
}

完整数组:

array:1 [▼
  0 => Port {#336 ▼
    #privatePort: 80
    #publicPort: 32780
    #type: "tcp"
  }
]

我使用docker-php sdk收到此错误。任何人都知道发生了什么事?

完整代码:

public function dockerContainers()
{
    $docker = new \Docker\Docker();
    $containerManager = $docker->getContainerManager();
    $containers = $containerManager->findAll();

    $data = [];
    $x=0;
    foreach ($containers as $container) {
        $ports = $container->getPorts();
        // dd($ports[0]);
        $ports = $ports[0];
        $privatePort = $ports->getPrivatePort();
        $publicPort = $ports->getPublicPort();
        $data[$x++] = [
            'id'    => $container->getId(),
            'state'  => $container->getState(),
            'names'  => $container->getNames(),
            'image'  => $container->getImage(),
            'status' => $container->getStatus(),
            'ports'  => [
                'privatePort' => $privatePort,
                'publicPort'  => $publicPort
            ]
        ];
    }

    return view('containers', [ 'containers' => $data ]);
}

1 个答案:

答案 0 :(得分:0)

这是因为您的speed.rate = speedIncrement之一没有container,最好使用laravel collect()方法,使您的数组成为集合对象,然后您可以使用可用的集合方法。 请尝试以下代码...

ports