You need to enable JavaScript to run this app. PHP 对象数组按coords字段检索目标项并存储对应数据的实现方法
优惠活动
大模型
产品
解决方案
定价
更多

PHP 对象数组按coords字段检索目标项并存储对应数据的实现方法

匹配失败的核心原因

你的数组每个元素都是*stdClass对象*,in_array只会对比数组顶层元素的整体值,不会深入对象内部读取coords属性做字段匹配,自然无法定位到目标项。

直接可用的实现方案

通过数组遍历逐行校验对象的coords属性值,匹配到目标后直接提取属性存入变量即可,参考代码:

// 定义检索的目标coords值
$target = "60:58";
// 初始化三个存储属性值的变量
$coordsVal = $cityVal = $nameVal = null;

// 遍历源数组
foreach ($sourceArray as $item) {
    // 严格匹配coords字段值
    if ($item->coords === $target) {
        // 提取三个属性值存入独立变量
        $coordsVal = $item->coords;
        $cityVal = $item->city;
        $nameVal = $item->name;
        // 匹配到后直接跳出循环,避免无意义的遍历
        break;
    }
}

// 非空判断确认是否匹配成功
if ($coordsVal !== null) {
    // 后续可直接使用这三个变量开展业务逻辑
}

可选简化写法:如果源数组数据量不大,不需要提前中断遍历,也可以用array_filter快速筛选匹配项,代码更简洁:

$target = "60:58";
$matchedList = array_filter($sourceArray, function($item) use ($target) {
    return $item->coords === $target;
});

if (!empty($matchedList)) {
    $firstMatch = reset($matchedList);
    $coordsVal = $firstMatch->coords;
    $cityVal = $firstMatch->city;
    $nameVal = $firstMatch->name;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.13 17:54:09