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

如何将两个数组映射生成扁平关联数组(PHP场景)

如何将状态ID计数数组与状态名称数组关联为扁平关联数组?

问题背景

现有两个数组:

  1. 状态ID与记录数数组:
[
    ["status" => NULL, "number" => "2355"],
    ["status" => "1", "number" => "1"],
    ["status" => "2", "number" => "1"],
    ["status" => "3", "number" => "1"],
    ["status" => "4", "number" => "1"],
    ["status" => "7", "number" => "1"]
]
  1. 状态名称数组:
[
    "Undelivered",
    "Sent",
    "Bounced",
    "Delivered",
    "Opened",
    "Clicked",
    "Logged In",
    "Completed",
    "Committed"
]

需要将它们关联成键为状态名称、值为对应记录数的扁平关联数组,最终期望输出:

[
    "Undelivered" => "2355",
    "Sent" => "1",
    "Bounced" => "1",
    "Delivered" => "1",
    "Opened" => "1",
    "Completed" => "1"
]

解决方案

通过两步转换实现:先将计数数组转为以状态索引为键的映射表,再遍历名称数组匹配对应计数,过滤无数据的状态。

完整代码如下:

// 获取原始数据
$data = $this->_get_email_status();
$statii = $this->model->option_status;

// 第一步:构建状态索引到记录数的映射表
// 将NULL状态映射为索引0,其他状态ID转为整数作为索引
$statusCountMap = [];
foreach ($data as $item) {
    $statusKey = $item['status'] === null ? 0 : (int)$item['status'];
    $statusCountMap[$statusKey] = $item['number'];
}

// 第二步:遍历状态名称数组,生成目标扁平数组
$result = [];
foreach ($statii as $index => $statusName) {
    // 只保留有对应记录数的状态
    if (isset($statusCountMap[$index])) {
        $result[$statusName] = $statusCountMap[$index];
    }
}

// 输出结果
print_r($result);

代码说明

  • 第一步的$statusCountMap是为了快速匹配:把原始计数数组的结构转换为[状态索引 => 记录数],其中NULL对应名称数组的第一个元素(索引0),数字类型的状态ID直接转为整数作为索引。
  • 第二步遍历状态名称数组时,仅将存在对应记录数的状态加入结果数组,自动过滤掉无数据的状态(比如"Clicked"、"Logged In"等),最终得到符合需求的扁平关联数组。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 18:10:28