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

PHP如何从嵌套array_map的处理结果中获取指定属性name?

实现方案

原有代码问题

  1. 调用array_map时未传入要遍历的目标数组$myArray,逻辑不完整
  2. 嵌套了多余的内层array_map,不需要遍历objectValue的所有字段,直接取name属性即可
  3. 仅判断了is_object场景,未兼容objectValue为数组的情况(你给出的示例里objectValue本身就是数组格式)
  4. 缺少字段存在性判断,直接取值容易触发Notice级别错误

修正后代码(兼容数组/对象格式的objectValue)

if (is_array($myArray)) {
    return array_map(
        static function ($item) {
            $objectValue = $item['objectValue'] ?? null;
            // 处理objectValue为数组的情况
            if (is_array($objectValue)) {
                return $objectValue['name'] ?? null;
            }
            // 处理objectValue为对象的情况
            if (is_object($objectValue)) {
                return $objectValue->name ?? null;
            }
            return null;
        },
        $myArray // 传入待遍历的原数组
    );
}

执行后输出结果为:['toto', 'tata'],如果你需要保留name作为键名,将对应return语句改为return ['name' => $objectValue['name']]即可。

如果你的运行环境是PHP7.4及以上版本,可以用箭头函数简化写法:

if (is_array($myArray)) {
    return array_map(
        fn($item) => isset($item['objectValue']) ? 
            (is_array($item['objectValue']) ? $item['objectValue']['name'] : $item['objectValue']->name) 
            : null,
        $myArray
    );
}

补充说明

你给出的数组示例存在语法问题,缺少objectValue后的数组括号、子元素之间的逗号,标准写法如下:

$myArray = [
    [
        'value1' => 1,
        'value2' => 2,
        'value3' => 3,
        'objectValue' => [
            'name' => 'toto',
            'age'  => 7,
            'sexe' => 'M'
        ]
    ],
    [
        'value1' => 11,
        'value2' => 22,
        'value3' => 33,
        'objectValue' => [
            'name' => 'tata',
            'age'  => 77,
            'sexe' => 'F'
        ]
    ]
];

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 16:36:02