You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

合并不同结构二维数组:将图片数组内容并入日期/URL数组

多维数组合并:解决Undefined array key错误

我需要将第二个数组中的图片对象合并到第一个数组中,两个数组的结构如下:

第一个数组(含日期/URL)

array:2 [
  0 => array:3 [
    0 => array:2 [
      "startDate" => "2022-01-01"
      "endDate" => "2022-01-31"
    ]
    1 => array:2 [
      "startDate" => "2022-02-01"
      "endDate" => "2022-02-28"
    ]
    2 => array:4 [
      "startDate" => ""
      "endDate" => ""
      "bannerUrl" => "https://commons.wikimedia.org/wiki/File:Red_rose_flower_detailed_imge.jpg"
      "imageTarget" => "image Target"
    ]
  ]
  1 => array:1 [
    0 => array:2 [
      "startDate" => "2022-01-01"
      "endDate" => "2022-01-15"
    ]
  ]
]

第二个数组(含图片对象)

array:2 [
  0 => array:2 [
    0 => array:1 [
      "image" => {"image A object...."}
    ]
    1 => array:1 [
      "image" => {"image B object...."}
    ]
  ]
  1 => array:1 [
    0 => array:1 [
      "image" => {"image C object...."}
    ]
  ]
]

我尝试了以下代码来合并:

foreach ($items as $key => $item) {
    for ($i = 0; $i < count($item); ++$i) {
        $executionArray[$key][$i] = $item[$i];
        if (isset($files[$key])) {
            if (isset($executionArray[$key][$i])) {
                $executionArray[$key][$i]['image'] = $files[$key][$i]['image'];
            }
        }
    }
}

但运行后报错:Undefined array key 2

问题原因

第一个数组的$items[0]包含3个子元素(索引0、1、2),但第二个数组对应的$files[0]只有2个子元素(索引0、1)。当循环到i=2时,$files[0][2]不存在,直接访问就会触发数组键未定义的错误。

修复后的代码

$executionArray = [];
foreach ($items as $key => $item) {
    foreach ($item as $i => $subItem) {
        // 复制原数组的当前子元素
        $executionArray[$key][$i] = $subItem;
        // 严格检查对应位置的图片是否存在,避免键未定义错误
        if (isset($files[$key][$i]['image'])) {
            $executionArray[$key][$i]['image'] = $files[$key][$i]['image'];
        }
    }
}

说明

  • 使用foreach遍历子元素比for循环更安全,无需依赖count(),也能自动匹配每个子元素的索引。
  • 增加isset($files[$key][$i]['image'])的检查,确保只有当对应位置存在图片时才赋值,不存在则跳过,避免报错。

内容的提问来源于stack exchange,提问作者user1687891

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 04:24:25