php - 使用 Laravel 更新嵌套数组

标签 php arrays laravel-5.1

首先抱歉,我只用 php 开发了一个月,我不知道如何用 laravel 更新它

我想更新多张照片。

照片有标题说明等

我的问题是我不知道该怎么做。

我尝试了以下方法

public function update(Request $request, Photo $photo)
{
    // loop through array of id's
    foreach ($request->photo_id as $id)
    {
        // find 
        $photos = $photo->find($id);
        // loop throug input fields
        foreach ($request->except('_token', 'tags', 'photo_id') as $key => $value)
        {
            $photos->$key = $value;
            $photos->save();
        }
    }
    die();
}  

出现以下错误

preg_replace(): Parameter mismatch, pattern is a string while replacement is an array

所以我发现问题出在值上

结果是这样的

关键变量

string(5) "title"
string(10) "country_id"
string(7) "city_id"
string(11) "category_id"
string(9) "cruise_id"
string(12) "itinerary_id"
string(4) "desc"
string(6) "people"
string(5) "title"
string(10) "country_id"
string(7) "city_id"
string(11) "category_id"
string(9) "cruise_id"
string(12) "itinerary_id"
string(4) "desc"
string(6) "people"

值变量结果

array(2) {
  [0]=>
  string(9) "title one"
  [1]=>
  string(9) "title two"
}
array(2) {
  [0]=>
  string(1) "1"
  [1]=>
  string(1) "1"
}
array(2) {
  [0]=>
  string(1) "1"
  [1]=>
  string(1) "1"
}
array(2) {
  [0]=>
  string(0) ""
  [1]=>
  string(0) ""
}
array(2) {
  [0]=>
  string(1) "1"
  [1]=>
  string(0) ""
}
array(2) {
  [0]=>
  string(1) "1"
  [1]=>
  string(0) ""
}

我尝试了几次其他尝试,但没有任何效果

有人可以帮我解决这个问题吗?

最佳答案

在不了解更多有关将请求对象传递给您的信息的情况下,我无法详细说明,但您可能希望让您的请求对象看起来像这样:

'photos' => [
    {
        'id' => 1,
        'title' => 'title one',
        // more properties ....
    },
    {
        'id' => 2,
        'title' => 'title two',
        // more properties ....
    },
]

然后尝试这样的事情:

public function update(Request $request)
{
    // Loop through the request photo id's
    $request->photos->each(function($photo) use ($request) {
       // Return the photo object you want to update
       $photo = Photo::find($photo->id);

       // Get the things you want from the request and update the object
       $photo->title= $request[$photo_id]->title;

       // Save the object
       $photo->save();
    })
}

您可能还想尝试 dd(); 函数而不是 die();。它使调试变得更加容易。

关于php - 使用 Laravel 更新嵌套数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31097526/

相关文章:

php - RouteCollection.php 中的 MethodNotAllowedHttpException 第 200 行 :

php - Facebook SDK v4 和 Graph Api 2.x 在粉丝页面墙中自动发布

php - MySQL - 如何规范化包含分隔符分隔的 ID 的列

javascript - Object.assign - 合并数组值

java - 如何在数组中生成随机数,使其总和达到定义的总数?

php - Laravel 5.1 : How to set Route for update record

php - Laravel 5.1 防止 CSRF 不匹配抛出异常

php - 向下舍入到最接近的 50 或 00 的最简单方法

php - [Microsoft][SQL Server Native Client 11.0][SQL Server]无效的对象名称

java - 删除重复的数组条目