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

PHP如何检查多维数组存在order_type为parent元素并取对应order_date

你原有代码不生效的原因是:in_array()默认只会检查外层数组的直接元素,而你$conversion[$cohort_check]的每个元素都是子数组,自然无法匹配到字符串parent。

实现方案

方案1:foreach遍历(兼容性最好、效率最高)

遍历数组,匹配到第一个符合条件的元素就终止循环,不需要遍历整个数组:

$has_parent = false;
$first_parent_order_date = '';

foreach ($conversion[$cohort_check] as $item) {
    if ($item['order_type'] === 'parent') {
        $has_parent = true;
        $first_parent_order_date = $item['order_date'];
        break; // 匹配到第一个就退出循环,避免多余遍历
    }
}

// 判断存在时的逻辑
if ($has_parent) {
    echo "subscribed!";
    // 可直接使用 $first_parent_order_date 拿到对应日期,你的示例中取值为21-03
    echo "首个parent类型订单的日期是:" . $first_parent_order_date;
}

方案2:使用内置数组函数(代码更简洁)

通过array_column()提取所有order_type字段值后再做判断,适合不需要兼容PHP 5.5以下版本的场景:

// 提取所有order_type字段组成新数组
$all_order_types = array_column($conversion[$cohort_check], 'order_type');
// 查找parent对应的第一个索引
$parent_index = array_search('parent', $all_order_types);

if ($parent_index !== false) {
    echo "subscribed!";
    $first_parent_order_date = $conversion[$cohort_check][$parent_index]['order_date'];
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 16:15:07