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

PHP如何按id合并两个数组 无匹配id时补全布尔值字段

数组合并实现方案

问题说明

你之前使用array_merge达不到预期,是因为该函数仅按数组索引进行合并/覆盖,不会根据自定义的id字段做关联匹配,需要先对已分配条目做索引转换,再遍历全量ID数组做匹配赋值。

原代码笔误修正提示

  1. 全量ID数组初始化变量为$ids,但循环内赋值写为$id[],变量名不一致
  2. 已分配条目赋值时,price字段错误赋值为未定义的$available,应该使用前面声明的$price变量

完整实现代码

// 1. 获取全量自定义文章ID数组
$all_posts = get_posts(array(
    'fields'          => 'id',
    'posts_per_page'  => -1,
    'post_type'       => 'items'
));
$all_ids = array();
foreach($all_posts as $a){
    $all_ids[] = $a->ID;
}

// 2. 获取当前页面分配的条目,转换为ID为键的索引数组,降低后续匹配开销
$items = get_field('items');
$assigned_map = array();
foreach($items as $p){ 
    $id = $p["select_item"][0]->ID;
    $price = $p["price"];
    $live = $p["live"];
    $assigned_map[$id] = [
        "price" => $price,
        "live"  => $live
    ];
}

// 3. 按规则合并生成最终数组
$merged_result = array();
foreach($all_ids as $id){
    if(isset($assigned_map[$id])){
        $merged_result[] = [
            "id"    => $id,
            "price" => $assigned_map[$id]['price'],
            "live"  => $assigned_map[$id]['live']
        ];
    } else {
        $merged_result[] = [
            "id"    => $id,
            "price" => false,
            "live"  => false
        ];
    }
}

逻辑说明

  • 先将已分配条目转换成以ID为键的关联数组$assigned_map,匹配时间复杂度为O(1),比每次遍历全量已分配条目匹配效率更高
  • 遍历全量ID数组,直接从$assigned_map中查找对应ID的配置,存在则取值,不存在则两个字段默认设为false,完全符合需求的合并规则

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 08:51:03