PHP foreach无法回显值

时间:2019-01-24 21:15:19

标签: php foreach

我确定我缺少一些简单的东西,但是下面是一个foreach循环,如果我执行$ value的var_dump,那么我将看到所有内容:

foreach ($vals as $key => $value) {  
  var_dump($value); 
}

以下是var_dump的一部分:

array (size=4)
  'tag' => string 'MAILSERVICE' (length=11)
  'type' => string 'complete' (length=8)
  'level' => int 4
  'value' => string 'Priority Mail Express 2-Day<sup>™</sup>' (length=57)

array (size=4)
  'tag' => string 'RATE' (length=4)
  'type' => string 'complete' (length=8)
  'level' => int 4
  'value' => string '61.15' (length=5)

array (size=3)
  'tag' => string 'POSTAGE' (length=7)
  'type' => string 'close' (length=5)
  'level' => int 3

array (size=4)
  'tag' => string 'POSTAGE' (length=7)
  'type' => string 'open' (length=4)
  'level' => int 3
  'attributes' => 
    array (size=1)
      'CLASSID' => string '2' (length=1)

array (size=4)
  'tag' => string 'MAILSERVICE' (length=11)
  'type' => string 'complete' (length=8)
  'level' => int 4
  'value' => string 'Priority Mail Express 2-Day<sup>™</sup> Hold For Pickup' (length=73)

array (size=4)
  'tag' => string 'RATE' (length=4)
  'type' => string 'complete' (length=8)
  'level' => int 4
  'value' => string '61.15' (length=5)

看到这些结果之后,我将foreach循环更改为以下内容,以为我将只使用邮件服务及其价格,而只是空白的页面:

foreach ($vals as $key => $value) {  
  if ($value[$key]['tag'] == "MAILSERVICE") {
    echo $value[$key]['value'];
  } 
  if ($value[$key]['tag'] == "RATE") {
    echo $value[$key]['value'];
  } 
}

使用error_reporting(E_ALL); ini_set('display_errors', 1);

显示未定义的索引,但是如果我只是执行var_dump($ value),这些警告是相同的

我知道这很简单,我想念了

2 个答案:

答案 0 :(得分:0)

感谢@Dharman向我展示了光线:

foreach ($vals as $key => $value) {  
  if ($vals[$key]['tag'] == "MAILSERVICE") {
    echo $vals[$key]['value'];
  } 
  if ($vals[$key]['tag'] == "RATE") {
    echo $vals[$key]['value'];
  } 
}

答案 1 :(得分:0)

$value是由您提供的4个项目组成的数组,我想未定义的索引可能是$value[$key]而不是

$value[$key]['value']

您应该使用

$value['value']