簡體   English   中英

PHP-檢查多維數組中的鍵是true還是false

[英]PHP - check if key in multidimensional array is true or false

我試圖基於多維數組中的三個布爾值來設置變量的值,但是在訪問它時遇到了麻煩。 我對PHP和Javascript有點陌生。

在我的表單數據進行var_dump(使用$ http從angular傳遞到外部PHP文件)之后,我留下了:

array(3) {
  ["selectedServices"]=>
  array(3) {
    ["test"]=>
    bool(true)
    ["test2"]=>
    bool(false)
    ["test3"]=>
    bool(false)
  }
  ["otherstuff"]=>
  string(10) "coolfield"
  ["smsDelRep"]=>
  bool(false)
}

現在,我正在嘗試基於“ selectedServices”創建一個變量,但是到目前為止所有嘗試都失敗了,我什至無法訪問它。

目前,這是我所擁有的:

$_POST = json_decode(file_get_contents('php://input'), true);

    $selectedServices = array($_POST['selectedServices']);
    if (in_array('test', $selectedServices, true)) {
        $allowedServices = '1';
        var_dump($allowedServices);

但是我沒有得到var_dump,所以我猜if語句返回false。 但為什么?

In_array檢查值,而不是鍵,您可以執行以下操作:

if(isset($selectedServices['test']) {
  //
}

編輯:這不是一個完美的解決方案,如果$ selectedServices ['test']為null,它將無法正常工作

使用array_key_exist代替:

if(array_key_exists('test', $selectedServices)) {
  //
}

但是您的代碼中有一個錯誤:

 $selectedServices = array($_POST['selectedServices']);

應該

$selectedServices = $_POST['selectedServices'];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM