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

如何对比字符串数组索引并获取对应数组元素值?

解决方案

首先你当前的foreach代码逻辑有误:你把$row(数组的元素值)赋值给了$index_of_count_per_slot,这根本没拿到数组的索引,自然没法和$index_to_compare做匹配。下面给你两种实用的实现方式:

方法一:直接遍历目标索引数组取值

这种方式直观易懂,还能额外处理索引不存在的情况:

$count_per_slot = [ "12", "9", "67", "120", "9", "67", "7" ];
$index_to_compare = [ "3", "4" ];

$matched_values = [];
foreach ($index_to_compare as $target_idx) {
    // 先检查索引是否存在,避免Undefined offset报错
    if (isset($count_per_slot[$target_idx])) {
        $matched_values[] = $count_per_slot[$target_idx];
    }
}

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

执行后会得到:Array ( [0] => 120 [1] => 9 )

方法二:用数组函数快速实现

利用array_flip和array_intersect_key组合,代码更简洁:

$count_per_slot = [ "12", "9", "67", "120", "9", "67", "7" ];
$index_to_compare = [ "3", "4" ];

// 把目标索引数组转成键为索引的数组,再取键的交集
$target_keys = array_flip($index_to_compare);
$matched_values = array_intersect_key($count_per_slot, $target_keys);

// 可选:如果需要重置结果数组的索引(默认会保留原数组的索引3、4)
$matched_values = array_values($matched_values);

print_r($matched_values);

执行结果和方法一一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 13:20:28