【问题标题】:Check if something exists in array检查数组中是否存在某些东西
【发布时间】:2014-05-12 02:47:49
【问题描述】:

我在 wordpress 中编码 if 语句时遇到了一点问题。 我的插件将自定义注册字段存储在数据库的一行中,比如说“custom_fields”。当我使用 get_user_meta 打印 custom_fields 时,我得到了存储在那里的所有信息的数组,例如:

Array ( [0] => Array ( [invoice_company_name] => x [invoice_nip] => x [invoice_street] => x [invoice_street_number] => x [invoice_post_code] => x [invoice_city] => x [invoice_country] => x [birth_date] => x [birth_city] => x [district] => x ) ) 

我想检查是否所有以 invoice 开头的字段都存在。当然,“x”在哪里,哪里有真正的价值。

好吧,我找到了函数 in_array(),所以尝试做这样的事情,但它不起作用

$user_ID = get_current_user_id();
$all_meta_for_user = get_user_meta( $user_ID, 'wp_s2member_custom_fields', false );
print_r( $all_meta_for_user );
if (in_array("[invoice_company_name]", $all_meta_for_user)) {
echo "exist";} else {echo 'dont exist';}

我得到'不存在' :) 出了什么问题? 另外,我可以一次检查所有值吗?像 in_array([1st]&&[2nd]&&[3rd]) 之类的东西?

谢谢!

【问题讨论】:

  • 删除括号:in_array("[invoice_company_name]", $all_meta_for_user))in_array("invoice_company_name", $all_meta_for_user))

标签: php arrays wordpress


【解决方案1】:

试试看

if (in_array("invoice_company_name", $all_meta_for_user[0])) {

【讨论】:

    【解决方案2】:

    如果您的数组是多维的,您可以使用 array_key_exists() 键搜索:

    foreach($all_meta_for_user as $key=>$val){
      if (array_key_exists('invoice_company_name', $val)) 
        {
          echo "exist in key ".$key;
        } 
      else 
        {
          echo "does not exist in key ".$key;
        }
    }
    

    Demo

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-06-04
      • 1970-01-01
      • 2012-03-12
      • 2017-02-12
      • 1970-01-01
      • 2022-11-29
      • 2012-05-11
      相关资源
      最近更新 更多