简体   繁体   English

PHP-检查多维数组中的键是true还是false

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

I'm trying to set the value of a variable based on three booleans from a multidimensional array but I'm having trouble accessing it. 我试图基于多维数组中的三个布尔值来设置变量的值,但是在访问它时遇到了麻烦。 I'm kinda new to PHP and Javascript. 我对PHP和Javascript有点陌生。

After a var_dump of my form data (passed using $http from angular to an external PHP-file) I'm left with: 在我的表单数据进行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)
}

Now I'm trying to create a variable based on "selectedServices" but all attempts so far has failed, I can't even access it. 现在,我正在尝试基于“ selectedServices”创建一个变量,但是到目前为止所有尝试都失败了,我什至无法访问它。

Currently this is what I have: 目前,这是我所拥有的:

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

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

But I'm not getting the var_dump so I'm guessing the if-statement returns false. 但是我没有得到var_dump,所以我猜if语句返回false。 But why? 但为什么?

In_array checks values, not keys, you could do : In_array检查值,而不是键,您可以执行以下操作:

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

EDIT : This is not a perfect solution, if $selectedServices['test'] is null it will not work 编辑:这不是一个完美的解决方案,如果$ selectedServices ['test']为null,它将无法正常工作

Use array_key_exist instead : 使用array_key_exist代替:

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

But there is an error in your code : 但是您的代码中有一个错误:

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

should be 应该

$selectedServices = $_POST['selectedServices'];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM