简体   繁体   中英

Updating a multidimensional array in laravel

I need some help on how to update a multidimensional array in PHP. I am using the following array to update a grid of images. The number of my images varies.First I upload and resize my images and then save them in the images field as Json in database.I set the image size to 300 by default and save it in thumb field. This my json images field that i store it in database:

[
  {
    "images": {
      "300": "/storage/uploads/300.1.png",
      "600": "/storage/uploads/600.1.png",
      "900": "/storage/uploads/900.1.png",
      "original": "/storage/uploads/1.png"
    },
    "thumb": "/storage/uploads/300.1.png"
  },
  {
    "images": {
      "300": "/storage/uploads/300.2.png",
      "600": "/storage/uploads/600.2.png",
      "900": "/storage/uploads/900.2.png",
      "original": "/storage/uploads/2.png"
    },
    "thumb": "/storage/uploads/300.2.png"
  },
  {},
  {}
]

For example, suppose I want to edit the size of the second image and change it from 300 to 600.This is the request log I get from the edit form.

array:3 [▼
  "_token" => "wZSerggegrgL1lcbhWZFwerfwerfwerfVx"
  "_method" => "patch"
  "imagesThumb" => array:4 [▼
    "/storage/uploads/300.1.png" => "/storage/uploads/300.1.png"
    "/storage/uploads/300.2.png" => "/storage/uploads/600.2.png"
    "/storage/uploads/300.3.png" => "/storage/uploads/300.3.png"
    "/storage/uploads/300.4.png" => "/storage/uploads/300.4.png"
  ]
]

How do I update the thumb of the second image?

You can use below solution. It was done by playing with array_flip() function. Replace address_to_json_file with the address of your json data.

$request = [
    "/storage/uploads/files/2020/ads/images/300_2020_12_25_26b48.1.png" => "/storage/uploads/files/2020/ads/images/300_2020_12_25_26b48.1.png",
    "/storage/uploads/files/2020/ads/images/300_2020_12_25_12567.2.png" => "/storage/uploads/files/2020/ads/images/600_2020_12_25_12567.2.png",
    "/storage/uploads/files/2020/ads/images/300_2020_12_25_6da51.4.png" => "/storage/uploads/files/2020/ads/images/300_2020_12_25_6da51.4.png",
    "/storage/uploads/files/2020/ads/images/300_2020_12_25_65509.png"   => "/storage/uploads/files/2020/ads/images/300_2020_12_25_65509.png",
];
$sample_json = json_decode(address_to_json_file, true);

for ($i = 0; $i < count($request); $i++) {
    $flipped_arr = array_flip($sample_json[$i]['images']);
    foreach ($flipped_arr as $new_key => $original_key) {
        if (!empty($request[$new_key]) && $new_key != $request[$new_key]) {
            $sample_json[$i]['images'] = $request[$new_key];
        }
    }
}

dd($sample_json);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM