【问题标题】:Itterate to a multidimensional array迭代到多维数组
【发布时间】:2020-02-17 01:04:18
【问题描述】:

我正在尝试遍历此数组以获取所有联赛值(league_id,name,type 等)

array:1 [▼
"api" => array:2 [▼
"results" => 970
"leagues" => array:970 [▼
  0 => array:13 [▼
    "league_id" => 1
    "name" => "World Cup"
    "type" => "Cup"
    "country" => "World"
    "country_code" => null
    "season" => 2018
    "season_start" => "2018-06-14"
    "season_end" => "2018-07-15"
    "logo" => "https://media.api-football.com/leagues/1.png"
    "flag" => null
    "standings" => 1
    "is_current" => 1
  ]
  1 => array:13 [▼
    "league_id" => 2
    "name" => "Premier League"
    "type" => "League"
    "country" => "England"
    "country_code" => "GB"
    "season" => 2018
    "season_start" => "2018-08-10"
    "season_end" => "2019-05-12"
    "logo" => "https://media.api-football.com/leagues/2.png"
    "flag" => "https://media.api-football.com/flags/gb.svg"
    "standings" => 1
    "is_current" => 0
  ]
  .......

但直到现在,使用以下代码:

$request = json_decode($request->getBody()->getContents(), true);
foreach ($request as $array=>$val) {
   foreach ($val['leagues'] as $id) {
        dd($id);
   }
}

我唯一能得到的是第一个数组,而不是其余的:

array:13 [▼
"league_id" => 1
"name" => "World Cup"
"type" => "Cup"
"country" => "World"
"country_code" => null
"season" => 2018
"season_start" => "2018-06-14"
"season_end" => "2018-07-15"
"logo" => "https://media.api-football.com/leagues/1.png"
"flag" => null
"standings" => 1
"is_current" => 1
]

有什么帮助吗?

【问题讨论】:

  • 您正在调用dd,转储并死掉,因此您在该循环的 first 迭代之后杀死脚本,因此您只访问该循环的第一个元素array ... 如果您只想转储数据而不终止执行,您可以使用 dump($var) 代替
  • 您是不是要这样做:foreach ($request['leagues'] as $league) { print_r($league); }。另外,如果您使用dd(),则表示die and dump,即它将打印变量的内容然后退出,这可能就是您只获得第一项的原因?

标签: php laravel multidimensional-array


【解决方案1】:

您正在调用的 dd() 函数在您的第一次迭代中终止脚本的执行。

来自Laravel Docs

dd 函数转储给定变量并结束脚本的执行。

如果您不想暂停脚本的执行,请改用转储函数。

像这样迭代它:

$request = json_decode($request->getBody()->getContents(), true);
foreach ($request['leagues'] as $id=>$league) {
  print_r(compact('id', 'league')); // To see the id and value array
}

希望对你有帮助,

【讨论】:

  • 删除dd
  • 不知道dd() 是什么。谢谢,
猜你喜欢
  • 2023-03-08
  • 2014-05-17
  • 1970-01-01
  • 2021-11-02
  • 2011-11-20
  • 2016-01-28
  • 2013-01-23
相关资源
最近更新 更多