php中如何判断多维无序数组是一样的?
PHPz
PHPz 2017-05-16 13:12:54
0
4
439

示例如下:
实际操作的是三维数组,而且数据量比较大。

$a = [ ['name'=>'jack', 'gender'=>'male'], ['age'=>18,'country'=>'China'] ]; $b = [ ['country'=>'China','age'=>18], ['gender'=>'male','name'=>'jack'] ];

除了遍历比较外有什么快捷有效的方式?
我现在的想法是先把数组按相同规则排序,json_encode后使用md5校验。不过目前似乎并不能很好的实现排序。
不知各位有什么很好的方法?

PHPz
PHPz

学习是最好的投资!

reply all (4)
大家讲道理

//Only applicable to purely associative arrays
function deep_ksort(&$arr) {

ksort($arr); foreach ($arr as &$a) { if (is_array($a) && !empty($a)) { deep_ksort($a); } }

}
deep_ksort($a);
deep_ksort($b);
if(json_encode($a) == json_encode($b)){

echo "两个数组相同";

}


//General method
//This function converts a multi-dimensional array into a one-dimensional array
function multiToSingle($arr, $delimiter = '->',$key = ' ') {

$resultAry = array(); if (!(is_array($arr) && count($arr)>0)) { return false; } foreach ($arr AS $k=>$val) { $k = is_numeric($k) ? 0 :$k; //若键是数字,则统一为0,避免索引不同导致数组的不同 $newKey = trim($key . $k . $delimiter); if (is_array($val) && count($val)>0) { $resultAry = array_merge($resultAry, multiToSingle($val, $delimiter, $newKey)); } else { $resultAry[] = $newKey . $val; } } return $resultAry;

}
//Judge whether two arrays are congruent
function judge($a,$b)
{

$single_A = multiToSingle($a); $single_B = multiToSingle($b); $arr1 = array_diff($single_A,$single_B); $arr2 = array_diff($single_B,$single_A);

if(empty($arr1) && empty($arr2)){

echo "两数组全等";

}else{

echo "不全等";

};

}

    迷茫

    You can take a look at this http://bbs.csdn.net/topics/36..., it should be useful to you!

      Peter_Zhu

      It’s very simple. After sorting by the same rules, convert the array into a string and compare whether the two strings are the same

        Ty80
        $a = [ ['name' => 'jack', 'gender' => 'male'], ['age' => 18, 'country' => 'China'] ]; $b = [ ['country' => 'China', 'age' => 18], ['gender' => 'male', 'name' => 'jack'] ]; function whetherDifferent($ele, $differentEle) { $toSingleArr = function ($target)use(&$toSingleArr){ //转换为一维数组的代码 return $target; }; $ele=$toSingleArr($ele); $differentEle=$toSingleArr($differentEle); ksort($ele,true); ksort($differentEle,true); return $ele===$differentEle; } var_dump(whetherDifferent($a, $b)); die;
          Latest Downloads
          More>
          Web Effects
          Website Source Code
          Website Materials
          Front End Template
          About us Disclaimer Sitemap
          php.cn:Public welfare online PHP training,Help PHP learners grow quickly!