在数组数组中插入数组元素的最佳方法



我正在尝试插入一个数组元素,其中包含数组中关系数据的id,将多条记录保存在CakePHP中。

数组的显示方式如下:

[Venue] => Array (
    [0] => Array (
        [name] => Great mansion
        [where] => New York
    )
    [1] => Array (
        [name] => Diamond palace
        [where] => London
    )
    [2] => Array (
        [name] => Palazzo Falcone
        [where] => Bologna
    )
)

我想将architect_id添加到数组的每个元素中,因此:

[Venue] => Array (
    [0] => Array (
        [name] => Great mansion
        [where] => New York
        [architect_id] => 33
    )
    [1] => Array (
        [name] => Diamond palace
        [where] => London
        [architect_id] => 33
    )
    [2] => Array (
        [name] => Palazzo Falcone
        [where] => Bologna
        [architect_id] => 33
    )
)

不确定我写的内容是否经过优化或可以改进:

$tot = count($this->request->data['Venue']);
for ($i = 0; $i < $tot; $i ++) {
    $this->request->data['Venue'][$i]['architect_id'] = $this->Architect->id;
}
$this->Venue->saveAll($this->request->data['Venue']);

代码有效,但这是这样做的好方法吗?

到目前为止

,您的解决方案很好。

foreach ($this->request->data['Venue'] as &$venue) {
  $venue['architect_id'] = $this->Architect->id;
}

也应该工作。自己决定,你觉得哪一个更具可读性。

最新更新