【问题标题】:Php array returning just one of an arrays values when looping throughphp数组在循环时只返回一个数组值
【发布时间】:2020-11-27 16:01:03
【问题描述】:

我有一个 php 数组,我正在尝试 var 转储值,以便查看返回的内容,但是当我使用 foreach 循环时,即使数组中有 2 个值,也只有一个值被转储.谁能告诉我代码中有什么不正确的地方?

PHP

$items = ($items['things']);
              
 foreach ($items as $value) {
      var_dump($value);  // Returns just the first thing in my items array i.e. "textbook"
 }

如果我 var_dump($items) 我得到一个这样的数组

array:2 [
  0 => "textbook"
  1 => "pencil"
] 

【问题讨论】:

  • 我运行了你的代码。它按预期给出了我的两个值。字符串(8)“教科书”字符串(6)“铅笔”
  • @JasonK foreach 循环中的 var_dump 给了你两个项目?嗯
  • 循环的每次运行都会给出 1 个值。

标签: php arrays


【解决方案1】:

它和我一起工作:

    $items = [
        'things' => ['a', 'b', 'c']
    ];
    $items = ($items['things']);
    foreach ($items as $item) {
        var_dump($item);
    }

结果:

string(1) "a"
string(1) "b"
string(1) "c"

【讨论】:

    猜你喜欢
    • 2014-04-10
    • 2017-04-03
    • 2011-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-11
    • 1970-01-01
    • 2013-08-25
    • 1970-01-01
    相关资源
    最近更新 更多