尽管索引存在,但未定义的索引仍然存在

Undefined Index persists although index exists

所以基本上我想创建一个有点像这样的列表数组

Array("Region")
 ['id'] => 1
 ['city'] => Array()

所以我从数据库中以这种方式获取区域:

$regions = Region::get()->keyById()->toArray();
$cities = City::get()->toArray();

然后

foreach($city as $city)
{
  $regions[city['region_id']]['cities'][] = city;
}

这工作中途,当我在 $region[index] 上使用 var_dump 时,它按预期显示 idcity

[0]=>
 ['id'] => 1
 other_contents
 ['city'] => Array()

var_dump $region['city'] returns 其适当的内容数组也是如此。

Array("Region")
 ['id'] => 1
 ['region_id'] => 1
 other_contents

但是,当我 var_dump-ed $region['id'] 时,它 returns 变成了 Undefined index: id

Table结构

Region
 id
 other_content

City
 id
 region_id
 other_content

错误在于此代码,

  $regions[city['region_id']]['cities'][] = city;

$regions是$region的数组,数组索引是0,1,2,不是region_id

你可以改成这个

$regions = Region::get()->keyById()->toArray();
foreach($regions as $region)
{   
    $region['cities'] = City::where('region_id', $region->id)->get()->toArray();
}

但我建议您使用 laravel 一对多 eloquent。

将此添加到区域模型

public function cities()
{
    return $this->hasMany('City', 'region_id');
}

将此添加到城市模型

public function region()
{
    return $this->belongsTo('Region', 'region_id');
}

然后在你的控制器中你可以使用

$region->cities()获取区域内所有城市。

希望对您有所帮助。