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

PHP匹配不同对象键值:从WCMP分类数组中提取符合条件的分类信息

错误原因说明

你之前的两个判断写法完全用错了函数的适用场景:

  • property_exists() 要求第一个参数为对象,第二个为要查询的属性名,你传入的两个参数都是数字类型的属性值,自然无法返回正确结果
  • array_key_exists() 要求第二个参数为数组,你传入的$cat_term->parent是数字类型,逻辑完全不成立,所以不会生效。

纯PHP实现方案

你可以先收集所有分类的parent值形成集合,再遍历筛选出term_id存在于该集合的分类即可,代码如下:

// 1. 收集所有分类的parent值,去重后得到所有被引用的父分类ID集合
$all_parent_ids = [];
foreach ($all_cats as $term) {
    if ($term->parent > 0) {
        $all_parent_ids[] = $term->parent;
    }
}
$all_parent_ids = array_unique($all_parent_ids);

// 2. 筛选符合条件的分类,提取term_id和name
$matched_terms = [];
foreach ($all_cats as $term) {
    if (in_array($term->term_id, $all_parent_ids)) {
        $matched_terms[] = [
            'term_id' => $term->term_id,
            'name' => $term->name
        ];
    }
}

// 打印结果验证
print_r($matched_terms);

用你提供的示例数组运行上述代码,输出结果为:

Array
(
    [0] => Array
        (
            [term_id] => 384
            [name] => Beers & Ales
        )
    [1] => Array
        (
            [term_id] => 387
            [name] => Wines
        )
)

完全符合需求。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 21:45:05