dongqiyang3711 2018-06-12 08:25 采纳率: 100%
浏览 141
已采纳

检查数组是否在另一个数组中并且它们是相同的

I have a $_SESSION['basket'] containing multiple arrays. I want to check if this $_SESSION['basket'] variable contains a specific array and that they have the same values.

For example, I want to check that $my_array which is an array is the same as $_SESSION['basket'][i].

$_SESSION['basket'] would contain multiple arrays as follow :

$_SESSION['basket'] = array(
  [0] => array(
    "key1" => "value1",
    "key2" => "value2"
  );
  [1] => array(
    "key3" => "value3",
    "key4" => "value4"
  );
  [2] => array(
    "key5" => "value5",
    "key6" => "value6"
  );
);

And $my_array would contain :

array(
  "key3" => "value3",
  "key4" => "value4"
);

So I want to make sure that the $my_array variable is contained inside the $_SESSION['basket'] variable and it's values are exactly the same obviously. Is there a way to do that without having to use a loop? If not, how to do it with a loop nonetheless?

  • 写回答

2条回答 默认 最新

  • dongyuruan2957 2018-06-12 08:51
    关注

    Well, you will have to use a loop. Even if you use any PHP API, it loops under the hood anyway.

    <?php 
    
    function checkIfExists($haystack,$needle){
      foreach($haystack as $each_needle){
          if(isEqual($each_needle,$needle)) return true;
      }
    
      return false;
    }
    
    function isEqual($test,$original){
      foreach($original as $each_key => $each_value){
        if(!isset($test[$each_key]) || $test[$each_key] !== $each_value) return false;
      }
    
      return count($test) === count($original);
    }
    
    
    $_SESSION['basket'] = array(
      array(
        "key1" => "value1",
        "key2" => "value2"
      ),
      array(
        "key3" => "value3",
        "key4" => "value4"
      ),
      array(
        "key5" => "value5",
        "key6" => "value6"
      )
    );
    
    $my_array = array(
      "key3" => "value3",
      "key4" => "value4"
    );
    
    var_dump(checkIfExists($_SESSION['basket'],$my_array));
    

    OUTPUT

    bool(true)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥35 平滑拟合曲线该如何生成
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站