【问题标题】:Why In_Array() PHP not working for multi-dimesional Array [closed]为什么 In_Array() PHP 不适用于多维数组 [关闭]
【发布时间】:2019-03-31 14:25:51
【问题描述】:

我正在尝试查看字符串是否在数组中,但是当尝试使用 in_array 搜索时,即使字符串在数组中,它也总是返回 false

  $array = { ["cardId"]=> int(233) ["mask"]=> string(14) "498765xxxx8769" ["brand"]=> string(4) "VISA" ["scheme"]=> string(4) "VISA" } }
    if(in_array('512345xxxx2346', $array)
    {
       echo "512345xxxx2346 found !!";
    }else {
      echo "512345xxxx2346 not found !!";
    }

输出

 512345xxxx2346 not found

请帮忙

【问题讨论】:

  • 您的示例按预期工作。好吧,有语法错误,但从逻辑上讲,我不会期待其他任何事情
  • @dan08 我已经更新了问题
  • 你能写一个可行的例子吗?
  • 这不是一个可用的 PHP 数组。而且你有语法错误。代码 sn-p 无法提供该输出
  • 你说的是关联数组吗?为什么你一直在谈论多维数组而不包括有效的minimal reproducible example????

标签: php arrays laravel codeigniter-3


【解决方案1】:

如果你有多张卡片,你可以遍历它们并检查每一张。

$cards = [["cardId" => 233, "mask" => "512345xxxx2346"], ["cardId" => 234, "mask" => "498765xxxx8769"]]
foreach($card in $cards) {
  if (in_array("512345xxxx2346", $card)) {
    echo "512345xxxx2346 found!";
  } else {
    echo "512345xxxx2346 not found!";
  }
}

【讨论】:

    【解决方案2】:

    您的示例根本不起作用,而且结果无论如何都是正确的,因为您在声明中以 4 开头并测试以 5 开头的 1。

    PHP 中的数组在方括号内声明,键与值之间用=> 分隔。

    $array = ["cardId" => 233, "mask" => "512345xxxx2346 ", "brand" => "VISA", "scheme" => "VISA"];
    if (in_array('512345xxxx2346 ', $array)) {
      echo "512345xxxx2346 found !!";
    } else {
      echo "512345xxxx2346 not found !!";
    }
    

    【讨论】:

    • @samuel 如果多维数组是这样的 (["cardId" => 233, "mask" => "512345xxxx2346", "brand" => "VISA", "scheme" = > "VISA"], ["cardId" => 234, "mask" => "498765xxxx8769", "brand" => "MASTERCARD", "scheme" => "MASTERCARD"]);
    【解决方案3】:

    您的语法完全错误,您要么在方括号 ["key" => value] 中声明数组,要么使用 array("key" => value)。

    使用正确的语法,您的示例将返回匹配 if 检查:

    $array = array(
       'cardId' => 233,
       'mask' => '498765xxxx8769',
       'brand' => 'VISA',
       'scheme' => 'VISA'
    );
    
    if(in_array('498765xxxx8769', $array)) {
       echo "498765xxxx8769 found !!";
    } else {
        echo "498765xxxx8769 not found !!";
    }
    

    假设您需要检查多张卡片,您可能需要一个多维数组,将数组放入数组中(以逗号分隔)。

    在这种情况下,您应该使用循环来检查第一个数组中的每个数组(或卡片):

    $array2 = array(
        array(
            'cardId' => 233,
            'mask' => '498765xxxx8769',
            'brand' => 'VISA',
            'scheme' => 'VISA'
    ),
        array(
            'cardId' => 367,
            'mask' => '839510xxxx0045',
            'brand' => 'VISA',
            'scheme' => 'VISA'
        )
    );
    
    $i = 1;
    foreach ($array2 as $a) {
        if (in_array('498765xxxx8769', $a)) {
            echo "Card " . $i . ": 498765xxxx8769 found !!" . "<br>";
        } else {
            echo "Card " . $i . ": 498765xxxx8769 not found !!" . "<br>";
        }
    $i++;
    }
    

    【讨论】:

      猜你喜欢
      • 2020-04-27
      • 1970-01-01
      • 2015-03-31
      • 1970-01-01
      • 2023-03-13
      • 1970-01-01
      • 2011-05-06
      相关资源
      最近更新 更多