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

PHP操作MySQL返回对象数组时如何仅修改指定字段不改动其他参数

优化实现代码(兼容你原有返回对象的逻辑)

$response = array();
$query = $wpdb->prepare('SELECT * FROM ' . self::get_services_table_name() . ' LIMIT %d', $limit);
// 直接获取对象数组,和你需要的返回结构一致
$results = $wpdb->get_results($query);

foreach ($results as $key => $item) {
    // 仅处理两个JSON格式字段,其余字段自动保留
    $item->price = json_decode($item->price);
    $item->service_timespan = json_decode($item->service_timespan);
    $response[$key] = $item;
}

return $response;

方案说明

  • $wpdb->get_results() 不传第二个参数时,默认返回 stdClass 对象组成的数组,和你最终要返回的结构完全匹配,不需要手动逐个赋值字段
  • 遍历过程仅修改指定的两个JSON字段,其余所有查询返回的字段都会原封不动保留
  • 如果你后续需要返回关联数组而非对象,可改用以下写法:
$response = array();
$query = $wpdb->prepare('SELECT * FROM ' . self::get_services_table_name() . ' LIMIT %d', $limit);
$results = $wpdb->get_results($query, ARRAY_A);

foreach ($results as $key => $item) {
    $item['price'] = json_decode($item['price']);
    $item['service_timespan'] = json_decode($item['service_timespan']);
    $response[$key] = $item;
}

return $response;

额外优化建议

如果你的JSON字段可能存在空值、非法JSON格式的情况,建议加判空逻辑避免抛出错误:

// 示例:对price字段加容错处理
$item->price = !empty($item->price) ? json_decode($item->price) : null;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 11:15:03