(PHP 5, PHP 7, PHP 8)
array_udiff_assoc — 使用額外的索引檢查計算陣列的差異,並透過回呼函式比較資料
使用額外的索引檢查計算陣列的差異,並透過回呼函式比較資料。
注意: 請注意,此函式僅檢查 n 維陣列的一個維度。當然,您可以透過使用例如
array_udiff_assoc($array1[0], $array2[0], "some_comparison_func");
來檢查更深的維度。
array(陣列)
第一個陣列。
arrays(陣列)
要比較的陣列。
value_compare_func(值比較函式)
比較函式必須回傳一個整數。若第一個參數小於、等於或大於第二個參數,則分別回傳小於零、等於零或大於零的整數。
排序回呼函式必須能夠處理來自任何陣列的任何值,且不論其原始提供的順序為何。這是因為每個個別的陣列在與其他陣列進行比較之前,會先自行排序。例如:
<?php
$arrayA = ["string", 1];
$arrayB = [["value" => 1]];
// $item1 和 $item2 可以是 "string"、1 或 ["value" => 1] 中的任何一個
$compareFunc = static function ($item1, $item2) {
$value1 = is_string($item1) ? strlen($item1) : (is_array($item1) ? $item1["value"] : $item1);
$value2 = is_string($item2) ? strlen($item2) : (is_array($item2) ? $item2["value"] : $item2);
return $value1 <=> $value2;
};
?>
array_udiff_assoc() 會傳回一個 陣列,其中包含所有在 array
中存在,但在其他任何引數中不存在的值。請注意,與 array_diff() 和 array_udiff() 不同,這裡的鍵值會被用於比較。陣列資料的比較是使用使用者提供的回呼函式來執行的。在這方面,其行為與 array_diff_assoc() 相反,後者使用內建函式進行比較。
範例 #1 array_udiff_assoc() 範例
<?php
class cr {
private $priv_member;
function __construct($val)
{
$this->priv_member = $val;
}
static function comp_func_cr($a, $b)
{
if ($a->priv_member === $b->priv_member) return 0;
return ($a->priv_member > $b->priv_member)? 1:-1;
}
}
$a = array("0.1" => new cr(9), "0.5" => new cr(12), 0 => new cr(23), 1=> new cr(4), 2 => new cr(-15),);
$b = array("0.2" => new cr(9), "0.5" => new cr(22), 0 => new cr(3), 1=> new cr(4), 2 => new cr(-15),);
$result = array_udiff_assoc($a, $b, array("cr", "comp_func_cr"));
print_r($result);
?>
以上範例會輸出:
Array ( [0.1] => cr Object ( [priv_member:private] => 9 ) [0.5] => cr Object ( [priv_member:private] => 12 ) [0] => cr Object ( [priv_member:private] => 23 ) )
在上面的例子中,您可以看到鍵值對 "1" => new cr(4)
存在於兩個陣列中,因此它不在函數的輸出結果中。