doubingjiu3199 2017-07-19 09:12
浏览 40
已采纳

在foreach循环外回显数组键时出错

Why is it that when I setup an array like this:

$plans[] = array(
  'provider'  => 'Boost Mobile',
  'plan'   => 'Unlimited Gigs',
   'url'  => 'https://www.boostmobile.com/#!/shop/plans/monthly-phone-plans/',
  'price'      => 50,
  'duration' => 'month',
}

I get an arror if I echo out a key like this:

echo $plans['plan'];

//Notice: Undefined index: plan

BUT when I echo it out inside a foreach array it outputs the value?

Any help is appreciated

  • 写回答

5条回答 默认 最新

  • douguio0185 2017-07-19 09:18
    关注

    You have define $plan with array so no need to take [] with $plans because it create multi dimentional array.

    I have added both example with and without [].

    Note

    $plans[] = array(); // It creates multi dimensional array
    $plans = array(); // It creates simple array
    

    Code

    <?php
    
    $plans[] = array(
      'provider'  => 'Boost Mobile',
      'plan'   => 'Unlimited Gigs',
       'url'  => 'https://www.boostmobile.com/#!/shop/plans/monthly-phone-plans/',
      'price'      => 50,
      'duration' => 'month');
    
    print_r($plans);
    echo $plans[0]['plan']; echo "
    
    ";
    
    $plans2 = array(
      'provider'  => 'Boost Mobile',
      'plan'   => 'Unlimited Gigs',
       'url'  => 'https://www.boostmobile.com/#!/shop/plans/monthly-phone-plans/',
      'price'      => 50,
      'duration' => 'month');
    
    print_r($plans2);
    echo $plans2['plan'];  
    

    Output

    Array
    (
        [0] => Array
            (
                [provider] => Boost Mobile
                [plan] => Unlimited Gigs
                [url] => https://www.boostmobile.com/#!/shop/plans/monthly-phone-plans/
                [price] => 50
                [duration] => month
            )
    
    )
    
    Unlimited Gigs
    
    Array
    (
        [provider] => Boost Mobile
        [plan] => Unlimited Gigs
        [url] => https://www.boostmobile.com/#!/shop/plans/monthly-phone-plans/
        [price] => 50
        [duration] => month
    )
    
    Unlimited Gigs
    

    Check Demo : Click Here

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

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?