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条)

报告相同问题?

悬赏问题

  • ¥15 关于自相关函数法和周期图法实现对随机信号的功率谱估计的matlab程序运行的问题,请各位专家解答!
  • ¥15 Python程序,深度学习,有偿私
  • ¥15 扫描枪扫条形码出现问题
  • ¥35 poi合并多个word成一个新word,原word中横版没了.
  • ¥15 【火车头采集器】搜狐娱乐这种列表页网址,怎么采集?
  • ¥15 求MCSCANX 帮助
  • ¥15 机器学习训练相关模型
  • ¥15 Todesk 远程写代码 anaconda jupyter python3
  • ¥15 我的R语言提示去除连锁不平衡时clump_data报错,图片以下所示,卡了好几天了,苦恼不知道如何解决,有人帮我看看怎么解决吗?
  • ¥20 关于URL获取的参数,无法执行二选一查询