无法将标量值用作数组(实际上是我试图访问不存在的数组键)


Cannot use a scalar value as an array (was actually me trying to access array key not existing)

我更新了问题标题,因为我希望得到的错误是"你试图访问一个不存在的密钥",在你们的评论中,我看到了这一点。无论如何,这是我最初的问题:

我一直收到错误

警告:不能在…中将标量值用作数组

从下面的第二行开始。getContainerSleepSettings()返回一个数组,但这应该不是问题吧?

   $helper = $this->get('biztv.helper.globalHelper');
    $containers = $helper->getContainers();
    //setup helper array with id's corresponding to the $containers (array of container entities)
    $containerHelper = array();
    foreach ($containers as $c) {
        $containerHelper[] = $c->getId();
        //Find out if sleeping
        $sleepSettings = $this->getContainerSleepSettings($c);
        var_dump( $containerHelper[$c->getId()]['wakeup'] = $sleepSettings['wakeup_s'] );
        var_dump( $containerHelper[$c->getId()]['sleep_s'] = $sleepSettings['sleep_s'] );
        if ( $sleepSettings['wakeup'] < date('U') && date('U') < $sleepSettings['sleep'] ) {
            $containerHelper[$c->getId()]['asleep'] = true; 
        }
        //Find out if online
        //$containerHelper[$c->getId()]['online'] = '$this->getOnlineAction( $c->getId() )';

        //find out if inherit layout/content

        //Find out if container receives mediasync

    }
    print_r($containerHelper);
    die;

private function getContainerSleepSettings($container) {
    //First find a container with sleepSettings
    while(!$container->getHourEnd() || !$container->getHourStart() ) {
        if ( $container->getParent() ) {
            $container = $container->getParent();
        }
        else {
            return null; //Infinity limited by level of parents - once no more parents we return null.
        }
    }
    //If we did find a parent with sleepSettings on it:

    $sleep['wakeup'] = $container->getHourEnd();
    $sleep['sleep'] = $container->getHourStart();
    if ($sleep['wakeup']) {
        $sleep['wakeup_s'] = $sleep['wakeup']->format('H:i');
    }
    else {
        $sleep['wakeup_s'] = '-';
    }

    if ($sleep['sleep']) {
        $sleep['sleep_s'] = $sleep['sleep']->format('H:i');
    }
    else {
        $sleep['sleep_s'] = '-';
    }
    return $sleep;          
}

在访问返回值之外的值之前,需要检查它是否是数组。。

$sleepSettings = $this->getContainerSleepSettings($c);
if ( is_array($sleepSettings) ) {
    var_dump( $containerHelper[$c->getId()]['wakeup'] = $sleepSettings['wakeup_s'] );
    var_dump( $containerHelper[$c->getId()]['sleep_s'] = $sleepSettings['sleep_s'] );
    if ( $sleepSettings['wakeup'] < date('U') && date('U') < $sleepSettings['sleep'] ) {
        $containerHelper[$c->getId()]['asleep'] = true; 
    }
} else {
   // $sleepSettings  is null
   // do something else..
}
$sleep = array();
$sleep['wakeup'] = $container->getHourEnd();