PHP如何从嵌套array_map的处理结果中获取指定属性name?
实现方案
原有代码问题
- 调用
array_map时未传入要遍历的目标数组$myArray,逻辑不完整 - 嵌套了多余的内层
array_map,不需要遍历objectValue的所有字段,直接取name属性即可 - 仅判断了
is_object场景,未兼容objectValue为数组的情况(你给出的示例里objectValue本身就是数组格式) - 缺少字段存在性判断,直接取值容易触发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
相关产品推荐
相关产品推荐

