检查值是否存在于对象数组中

时间:2018-07-13 12:24:39

标签: php

我正在使用一个API,该API接收$POST数据的PHP对象。我试图检查是否customFields中的'smsPhoneNumber'存在,但不确定如何执行此操作。

我目前可以使用以下方式检查“电子邮件”:

if ( property_exists( $data, 'email' ) ) {
  return true;
}

问题:如何检查“ smsPhoneNumber”是否存在?

-

var_dump:

object(stdClass)[1515]
  public 'email' => string 'email@email.com'
  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'

2 个答案:

答案 0 :(得分:1)

您可以使用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;
}

答案 1 :(得分:0)

使用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;
    }
}

这将被证明是非常有效的,并且易于阅读/维护。

相关问题