我正在做一个API,它可以接收一个PHP对象的 $POST
数据。我正试图检查customFields中的'smsPhoneNumber'是否存在,但不知道该怎么做。
目前我可以使用'email'来检查。
if ( property_exists( $data, 'email' ) ) {
return true;
}
问题:"如何检查'smsPhoneNumber'是否存在? 如何检查'smsPhoneNumber'是否存在?
--
var_dump:
object(stdClass)[1515]
public 'email' => string '[email protected]'
public 'customFields' =>
array (size=2)
0 =>
object(stdClass)[1512]
public 'name' => string 'Firstname'
public 'value' => string 'james'
1 =>
object(stdClass)[1514]
public 'name' => string 'smsPhoneNumber'
public 'value' => string '077'
你可以使用array_filter来获取你想要的自定义字段。
$phoneFields = array_filter($data->customFields, function($field) {
return $field->name === 'smsPhoneNumber';
});
这将只返回数组中名称属性等于smsPhoneNumber的对象。
if (!count($phoneFields)) {
// Phone not found
}
// or
if ($phone = current($phoneFields)) {
echo "The first phone number found is " . $phone->value;
}
使用这个方法的缺点是 array_filter()
来搜索子数组的值是。
array_filter()
一旦找到匹配值就不会停止;即使找到了匹配值,它也会继续迭代,直到到达数组的末端。你应该使用一种技术,允许早期的 break
return
.
我建议采用简单的 foreach()
附带 break
.
$foundIndex = null;
foreach ($data->customFields as $index => $customFields) {
if ($customFields->name === 'smsPhoneNumber') {
$foundIndex = $index;
// or $wasFound = true;
// or $smsNumber = $customFields->value;
break;
}
}
这将被证明是非常有效和易于阅读维护的。