2016-11-23 44 views
1

我有一个数组,每个数组都有一个值。如果语句在数组中?

下面是这样一个例子:

$sales_payload = array(
    'organization_id' => $organization_id, 
    'contact_id' => $contact_id, 
    'status' => 'Open', 
    'subject' => $_product->post_title." ".str_replace($strToRemove, "", $_POST['billing_myfield12']), 
    'start_date' => date("Y-m-d"), // set start date on today 
    'expected_closing_date' => date("Y-m-d",strtotime(date("Y-m-d")."+ 14 days")), // set expected closing date 2 weeks from now 
    'chance_to_score' => '10%', 
    'expected_revenue' => 0, //set the expected revenue 
    'note' => $_POST['order_comments'], 

    'progress' => array(
    'id'=>'salesprogress:200a53bf6d2bbbfe' //fill a valid salesprogress id to set proper sales progress 
    ), 

    "custom_fields"=> [[ 
    if(strpos($_POST['billing_myfield13'], 'ja') !== false) { [["actief_in_duitsland"=>1]] } 
    ]] 
); 

现在我试图填补某一阵列在我的代码这一个:

"custom_fields"=> [["actief_in_duitsland"=>1]] 

这工作。唯一的事情是我想在某种情况下值是=> 1。 这种情况是如果某个POST请求包含那么某些字符串使价值=> 1

我尝试这样做:

"custom_fields"=> [[ 
if(strpos($_POST['billing_myfield13'], 'ja') !== false) { [["actief_in_duitsland"=>1]] } 
]] 

所以

if(strpos($_POST['billing_myfield13'], 'ja') !== false) { [["actief_in_duitsland"=>1]] } 

如果$_POST['billing_myfield13']包含单词“JA”

then [["actief_in_duitsland"=>1]]

+0

不,你不能在数组定义中有'if'语句。但是,你可以使用ternarys,但是否合适是另一回事。 –

+0

或者您可以只分配比较的布尔结果 –

回答

3

您可以使用三元条件,这是一个if语句的快捷方式。下面是如何三元条件的例子作品:

有规律的,如果会这样写:

if("mycondition" == 1) 
{ 
    $boolean = true; 
} 
else { 
    $boolean = false; 
} 

与三元条件这一说法的等效会这样写如下:

$boolean = ("mycondition" == 1) ? true : false; 

您可能想要使用此快捷方式来实例化您的阵列,如下所示:

$sales_payload = [ 
    // ... 
    'custom_fields' => (strpos($_POST['billing_myfield13'], 'ja') !== false) ? [['actief_duitsland' => 1]] : [['actief_duitsland' => '???']], 
    // ... 
]; 

警告

您还应该为此语句定义一个else值。

1

如果阵列中声明不应该工作,你可以试试下面的代码

$actief_in_duitsland = (strpos($_POST['billing_myfield13'], 'ja') !== false) ? 1 : 0; 

$sales_payload = array(
    'organization_id' => $organization_id, 
    'contact_id' => $contact_id, 
    'status' => 'Open', 
    'subject' => $_product->post_title." ".str_replace($strToRemove, "", $_POST['billing_myfield12']), 
    'start_date' => date("Y-m-d"), // set start date on today 
    'expected_closing_date' => date("Y-m-d",strtotime(date("Y-m-d")."+ 14 days")), // set expected closing date 2 weeks from now 
    'chance_to_score' => '10%', 
    'expected_revenue' => 0, //set the expected revenue 
    'note' => $_POST['order_comments'], 

    'progress' => array(
    'id'=>'salesprogress:200a53bf6d2bbbfe' //fill a valid salesprogress id to set proper sales progress 
    ), 

    "custom_fields"=> [['actief_in_duitsland' => $actief_in_duitsland]] 
);