如何在运行if语句之前检查数组中的$ meta_key是否具有值

问题描述 投票:1回答:2

我正在研究一些代码,它将信息从自定义字段发布到数据库。

以下代码检查$ 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
2个回答
0
投票

您应该始终检查是否设置了变量并使用utlize短路运算符来减少条件的处理时间。由于您没有包含设置$ 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
}

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))) {
© www.soinside.com 2019 - 2024. All rights reserved.