2016-11-23 17 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]] 
);