【问题标题】:PHP - check if key in multidimensional array is true or falsePHP - 检查多维数组中的键是真还是假
【发布时间】:2016-02-19 10:03:57
【问题描述】:

我正在尝试根据多维数组中的三个布尔值设置变量的值,但我无法访问它。我对 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。但是为什么呢?

【问题讨论】:

  • 您想要检查数组键而不是搜索键作为值。
  • 你为什么将你的帖子包装在一个数组中?

标签: php angularjs webforms


【解决方案1】:

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'];

【讨论】:

  • 嗯,还是变成假的; if(isset($selectedServices['test']) { echo "yay"; else { echo "nay"; } } 给我 "nay" :(
猜你喜欢
  • 2020-01-30
  • 2018-06-01
  • 2021-11-23
  • 2019-01-21
  • 2019-08-09
  • 2019-12-24
  • 1970-01-01
  • 2016-05-10
  • 2020-12-31
相关资源
最近更新 更多