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

使用array_splice替换数组type键值失败的技术求助

解决PHP数组修改问题

我来帮你搞定这个问题~你当前的代码错误在于使用array_splice往数组开头插入了一个仅包含type的独立元素,而不是修改已生成的第一个子行程的type值。

问题分析

你原本的逻辑是:

  1. 生成一系列包含type: normal、start和end的子行程数组
  2. 当$trip['standard']存在时,用array_splice插入一个['type' => 'standard']的元素到数组开头
    这就导致数组第一个元素变成了单独的type值,而不是你想要的包含start和end的完整子行程对象。

修正后的代码

$trip['subtrips'] = [];
for ($i=0; $i<count($trip['locations'])-1; $i++) {
    array_push($trip['subtrips'], ['type' => 'normal', 'start' => $trip['locations'][$i], 'end' => $trip['locations'][$i+1]]);
}
// 检查standard标记是否存在,同时确保subtrips数组不为空(避免索引越界)
if(isset($trip['standard']) && !empty($trip['subtrips'])) {
    // 直接修改第一个子行程的type值
    $trip['subtrips'][0]['type'] = 'standard';
}

代码说明

  • 保留你原本生成子行程数组的逻辑,确保每个子行程都包含type、start和end三个键
  • 当$trip['standard']存在时,直接修改$trip['subtrips']数组第一个元素的type值为standard,而不是插入新元素
  • 增加!empty($trip['subtrips'])的判断,防止当$trip['locations']元素数量小于2时,subtrips为空数组导致访问索引[0]报错

这样修改后,你就能得到期望的输出:

Array (
    [0] => Array (
        [type] => standard
        [start] => Location 1
        [end] => Location 2
    )
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 19:23:11