【问题标题】:How to check if $meta_key in array has a value before running an if-statement如何在运行 if 语句之前检查数组中的 $meta_key 是否有值
【发布时间】:2018-09-09 03:10:31
【问题描述】:

我正在编写一些将自定义字段中的信息发布到数据库的代码。

以下代码检查是否存在 $meta_key

// Apply filters to keys
$this->keys = apply_filters('sc_meta_keys', $this->keys);

// See if the current meta_key is in the array keys
if($this->in_array_recursive($meta_key, $this->keys)) {

if($action == "add") {
//information from array gets added to DB
} 

}else{
//Do something else
}

但我不确定如何检查 meta_key 中是否有值,因为如果没有值存在,我不希望 if 语句运行。

该数组将始终具有键,但并非每个帖子都必须填充自定义字段。

【问题讨论】:

    标签: php wordpress if-statement multidimensional-array metadata


    【解决方案1】:

    您应该始终检查是否设置了变量,并使用短路运算符来减少条件句的处理时间。由于您没有包含设置 $meta_key 的逻辑,我会检查它是否已设置。

    $this->keys = apply_filters('sc_meta_keys', $this->keys);
    
    // See if the current meta_key is in the array keys
    if( isset( $meta_key ) && ! empty( $this->keys ) && $this->in_array_recursive( $meta_key, $this->keys ) ) {
    
        if($action == "add") {
            //information from array gets added to DB
        } 
    
        }
        else {
            //Do something else
    }
    

    【讨论】:

    • 不幸的是,它仍在传递信息。我将 sc_meta_keys 函数中的键设置如下$keys['lat'][] = "latitude";$keys['lng'][] = "longitude"; 是否将其视为一个字符串,尽管它是一个空字符串?
    • @MrBiggRJD 您正在设置数组值,因此它不会为空。
    【解决方案2】:

    也许你应该这样做。这将检查 $metakey 是否存在。

    // See if the current meta_key is in the array keys
    if (isset( $meta_key )) && (is_array($meta_key) && ($this->in_array_recursive($meta_key, $this->keys))) {
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-13
      • 1970-01-01
      • 2019-11-03
      • 1970-01-01
      • 1970-01-01
      • 2021-09-28
      相关资源
      最近更新 更多