【问题标题】:php check if value exists in associative array [duplicate]php检查关联数组中是否存在值[重复]
【发布时间】:2017-07-02 12:22:20
【问题描述】:

我有如下数组:

$import_emails = [];

$import_emails[]=[
    'to'=>$to,
    'from'=>$from,
     'cc'=>$cc,
     'subject'=>$subject,
    'text'=>$text,
    'date'=> date('Y-m-d H:i:s',strtotime($date))
];

数组数据示例:

Array
     (
    [0] => Array
    (
        [to] => nastya.gorobets95@gmail.com
        [from] => babboe1 babboe1 <test.babboe1@gmail.com>
        [cc] => 
        [subject] => Test Subject
        [text] => Test content.
        Please, write me later
        Thanks!

        [date] => 2017-06-29 18:04:53
    )

[1] => Array
    (
        [to] => Anastasia Gorobets <nastya.gorobets95@gmail.com>
        [from] => babboe1 babboe1 <test.babboe1@gmail.com>
        [cc] => babboesignal@edu-crm.com
        [subject] => Tema
        [text] => Bla bla bla
         Test email! :)

        [date] => 2017-07-02 11:55:50
    )

 )

如何检查数组 item ['to'] 中是否存在值,例如 'nastya' ? 也许它有一些功能?谢谢!

【问题讨论】:

  • foreach + strpos - 自己尝试一下。如果您遇到问题,请使用您尝试过的内容编辑您的问题。
  • 看看array_filter() 和array_search()。这应该会给你一些想法

标签: php arrays


【解决方案1】:

有时我使用array_column 将关联数组转换为平面数组。然后检查它是否存在。

$dataSubjectsValue = array_column($data, 'subject');
if (in_array('Test Subject', $dataSubjectsValue)) {
  // ...do your stuff
}

我认为这比使用 foreach 循环更具可读性。

【讨论】:

    【解决方案2】:

    你需要 foreach 你的数组。

    foreach ($import_emails as $key => $value) {
    
    $to = $value['to'];
    
    if($to == "nastya") {
    echo 'Found!';
    break;
    }
    
    }
    

    【讨论】:

      【解决方案3】:

      您想检查您的值是否存在于该数组值中。
      (你想在数组字段中找到“nastya”)

      if( isset( $import_emails[$incex_of_array]['to']) )
          if(strpos($import_emails[]['to'], 'youvalue'))
              // you action 
      

      【讨论】:

        猜你喜欢
        • 2015-10-09
        • 1970-01-01
        • 2021-02-13
        • 2017-09-05
        • 2012-08-02
        • 2011-12-14
        • 2017-11-24
        • 2016-06-22
        • 1970-01-01
        相关资源
        最近更新 更多