dongqiyang3711 2018-06-12 00: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 00: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条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部