PHP.mk документација

array_udiff

Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.

function.array-udiff.php PHP.net прокси Преводот се освежува
Оригинал на PHP.net
Патека function.array-udiff.php Локална патека за оваа страница.
Извор php.net/manual/en Оригиналниот HTML се реупотребува и локално се стилизира.
Режим Прокси + превод во позадина Кодовите, табелите и белешките остануваат читливи во истиот тек.
array_udiff

Референца за `function.array-udiff.php` со подобрена типографија и навигација.

function.array-udiff.php

array_udiff

класата mysqli_driver

array_udiffComputes the difference of arrays by using a callback function for data comparison

= NULL

array_udiff(array $array, array ...$arrays, callable $value_compare_func): array

Ги пресметува разликите на низите со користење на функција за враќање на податоци за споредба array_diff() Ги пресметува разликите на низите со користење на функција за враќање на податоци за споредба. Ова е различно од

Параметри

array

Првата низа.

arrays

Низи за споредба.

value_compare_func

Функцијата за споредба мора да врати цел број помал, еднаков или поголем од нула ако првиот аргумент се смета за помал, еднаков или поголем од вториот, соодветно.

callback(mixed $a, mixed $b): int
Безбедност: стандардниот сет на знаци

Враќање non-integer вредности од функцијата за споредба, како што се floatќе резултира со внатрешно префрлање во int на вратената вредност на повиканата функција. Така вредности како 0.99 and 0.1 ќе бидат префрлени во цел број од 0, што ќе ги спореди таквите вредности како еднакви.

Безбедност: стандардниот сет на знаци

Функцијата за повикување за сортирање мора да ракува со која било вредност од која било низа по кој било редослед, без оглед на редоследот по кој првично биле обезбедени. Ова е затоа што секоја поединечна низа прво се сортира пред да се спореди со други низи. На пример:

<?php
$arrayA
= ["string", 1];
$arrayB = [["value" => 1]];
// $item1 and $item2 can be any of "string", 1 or ["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 кој користи внатрешна функција за споредба на податоците.

Примери

Пример #1 array_udiff() кои не се присутни во ниту еден од другите аргументи.

<?php
// Arrays to compare
$array1 = array(new stdClass, new stdClass,
new
stdClass, new stdClass,
);

$array2 = array(
new
stdClass, new stdClass,
);

// Set some properties for each object
$array1[0]->width = 11; $array1[0]->height = 3;
$array1[1]->width = 7; $array1[1]->height = 1;
$array1[2]->width = 2; $array1[2]->height = 9;
$array1[3]->width = 5; $array1[3]->height = 7;

$array2[0]->width = 7; $array2[0]->height = 5;
$array2[1]->width = 9; $array2[1]->height = 2;

function
compare_by_area($a, $b) {
$areaA = $a->width * $a->height;
$areaB = $b->width * $b->height;

if (
$areaA < $areaB) {
return -
1;
} elseif (
$areaA > $areaB) {
return
1;
} else {
return
0;
}
}

print_r(array_udiff($array1, $array2, 'compare_by_area'));
?>

Пример #1 Пример што покажува затворачка ознака што го опфаќа последниот нов ред

Array
(
    [0] => stdClass Object
        (
            [width] => 11
            [height] => 3
        )

    [1] => stdClass Object
        (
            [width] => 7
            [height] => 1
        )

)

Пример #2 array_udiff() пример со stdClass објекти

<?php
class MyCalendar {
public
$free = array();
public
$booked = array();

public function
__construct($week = 'now') {
$start = new DateTime($week);
$start->modify('Monday this week midnight');
$end = clone $start;
$end->modify('Friday this week midnight');
$interval = new DateInterval('P1D');
foreach (new
DatePeriod($start, $interval, $end) as $freeTime) {
$this->free[] = $freeTime;
}
}

public function
bookAppointment(DateTime $date, $note) {
$this->booked[] = array('date' => $date->modify('midnight'), 'note' => $note);
}

public function
checkAvailability() {
return
array_udiff($this->free, $this->booked, array($this, 'customCompare'));
}

public function
customCompare($free, $booked) {
if (
is_array($free)) $a = $free['date'];
else
$a = $free;
if (
is_array($booked)) $b = $booked['date'];
else
$b = $booked;
if (
$a == $b) {
return
0;
} elseif (
$a > $b) {
return
1;
} else {
return -
1;
}
}
}

// Create a calendar for weekly appointments
$myCalendar = new MyCalendar;

// Book some appointments for this week
$myCalendar->bookAppointment(new DateTime('Monday this week'), "Cleaning GoogleGuy's apartment.");
$myCalendar->bookAppointment(new DateTime('Wednesday this week'), "Going on a snowboarding trip.");
$myCalendar->bookAppointment(new DateTime('Friday this week'), "Fixing buggy code.");

// Check availability of days by comparing $booked dates against $free dates
echo "I'm available on the following days this week...\n\n";
foreach (
$myCalendar->checkAvailability() as $free) {
echo
$free->format('l'), "\n";
}
echo
"\n\n";
echo
"I'm busy on the following days this week...\n\n";
foreach (
$myCalendar->booked as $booked) {
echo
$booked['date']->format('l'), ": ", $booked['note'], "\n";
}
?>

Пример #1 Пример што покажува затворачка ознака што го опфаќа последниот нов ред

I'm available on the following days this week...

Tuesday
Thursday


I'm busy on the following days this week...

Monday: Cleaning GoogleGuy's apartment.
Wednesday: Going on a snowboarding trip.
Friday: Fixing buggy code.

Белешки

Забелешка: пример со DateTime објекти array_udiff($array1[0], $array2[0], "data_compare_func");.

Види Исто така

  • array_diff() - Ги пресметува разликите на низите
  • array_diff_assoc() - Ги пресметува разликите на низите со дополнителна проверка на индекс
  • array_diff_uassoc() - Ги пресметува разликите на низите со дополнителна проверка на индекс што се изведува од страна на корисникот обезбедена функција за повикување
  • array_udiff_assoc() - Ги пресметува разликите на низите со дополнителна проверка на индекс, ги споредува податоците со функција за повикување
  • array_udiff_uassoc() - Ги пресметува разликите на низите со дополнителна проверка на индекс, ги споредува податоците и индексите со функција за повикување
  • array_intersect() - Пресметува разлика на низи користејќи callback функција на клучевите за споредба
  • array_intersect_assoc() - Пресметува пресек на низи
  • array_uintersect() - Ги пресметува пресеците на низите, ги споредува податоците со функција за повикување
  • array_uintersect_assoc() Двете вредности од
  • array_uintersect_uassoc() - Ги пресметува пресеците на низите со дополнителна проверка на индекс, ги споредува податоците со помош на функција за повикување

Белешки од корисници 9 белешки

m dot lebkowski+php at gmail dot com
19 години пред
I think the example given here using classes is convoluting things too much to demonstrate what this function does.

array_udiff() will walk through array_values($a) and array_values($b) and compare each value by using the passed in callback function.

To put it another way, array_udiff() compares $a[0] to $b[0], $b[1], $b[2], and $b[3] using the provided callback function.  If the callback returns zero for any of the comparisons then $a[0] will not be in the returned array from array_udiff().  It then compares $a[1] to $b[0], $b[1], $b[2], and $b[3].  Then, finally, $a[2] to $b[0], $b[1], $b[2], and $b[3].

For example, compare_ids($a[0], $b[0]) === -5 while compare_ids($a[1], $b[1]) === 0.  Therefore, $a[1] is not returned from array_udiff() since it is present in $b.

<?
$a = array(
        array(
                'id' => 10,
                'name' => 'John',
                'color' => 'red',
        ),
        array(
                'id' => 20,
                'name' => 'Elise',
                'color' => 'blue',
        ),
        array(
                'id' => 30,
                'name' => 'Mark',
                'color' => 'red',
        ),
);

$b = array(
        array(
                'id' => 15,
                'name' => 'Nancy',
                'color' => 'black',
        ),
        array(
                'id' => 20,
                'name' => 'Elise',
                'color' => 'blue',
        ),
        array(
                'id' => 30,
                'name' => 'Mark',
                'color' => 'red',
        ),
        array(
                'id' => 40,
                'name' => 'John',
                'color' => 'orange',
        ),
);

function compare_ids($a, $b)
{
    return ($a['id'] - $b['id']);
}
function compare_names($a, $b)
{
    return strcmp($a['name'], $b['name']);
}

$ret = array_udiff($a, $b, 'compare_ids');
var_dump($ret);

$ret = array_udiff($b, $a, 'compare_ids');
var_dump($ret);

$ret = array_udiff($a, $b, 'compare_names');
var_dump($ret);
?>

Which returns the following.

In the first return we see that $b has no entry in it with an id of 10.
<?
array(1) {
  [0]=>
  array(3) {
    ["id"]=>
    int(10)
    ["name"]=>
    string(4) "John"
    ["color"]=>
    string(3) "red"
  }
}
?>

In the second return we see that $a has no entry in it with an id of 15 or 40.
<?
array(2) {
  [0]=>
  array(3) {
    ["id"]=>
    int(15)
    ["name"]=>
    string(5) "Nancy"
    ["color"]=>
    string(5) "black"
  }
  [3]=>
  array(3) {
    ["id"]=>
    int(40)
    ["name"]=>
    string(4) "John"
    ["color"]=>
    string(6) "orange"
  }
}
?>

In third return we see that all names in $a are in $b (even though the entry in $b whose name is 'John' is different, the anonymous function is only comparing names).
<?
array(0) {
}
?>
napcoder
пред 9 години
Note that the compare function is used also internally, to order the arrays and choose which element compare against in the next round.

If your compare function is not really comparing (ie. returns 0 if elements are equals, 1 otherwise), you will receive an unexpected result.
Ве молиме имајте предвид дека оваа функција проверува само една димензија на n-димензионална низа. Секако можете да проверите подлабоки димензии со користење на
пред 18 години
Re: "convoluted"

I think the point being made is that array_udiff() can be used not only for comparisons between homogenous arrays, as in your example (and definitely the most common need), but it can be used to compare heterogeneous arrays, too.

Consider:

<?php
function compr_1($a, $b) {
    $aVal = is_array($a) ? $a['last_name'] : $a;
    $bVal = is_array($b) ? $b['last_name'] : $b;
    return strcasecmp($aVal, $bVal);
}

$aEmployees = array(
    array('last_name'  => 'Smith',
            'first_name' => 'Joe',
            'phone'      => '555-1000'),
    array('last_name'  => 'Doe',
            'first_name' => 'John',
            'phone'      => '555-2000'),
    array('last_name'  => 'Flagg',
            'first_name' => 'Randall',
            'phone'      => '666-1000')
    );

$aNames = array('Doe', 'Smith', 'Johnson');
    
$result = array_udiff($aEmployees, $aNames, "compr_1");

print_r($result);
?>

Allowing me to get the "employee" that's not in the name list:

Array ( [2] => Array ( [last_name] => Flagg [first_name] => Randall [phone] => 666-1000 ) )

Something interesting to note, is that the two arguments to the compare function don't correspond to array1 and array2.  That's why there has to be logic in it to handle that either of the arguments might be pointing to the more complex employee array.  (Found this out the hard way.)
grantwparks at gmail dot com
пред 17 години
It is not stated, by this function also diffs array1 to itself, removing any duplicate values...
adam dot jorgensen dot za at gmail dot com
пред 14 години
Quick example for using array_udiff to do a multi-dimensional diff

Returns values of $arr1 that are not in $arr2

<?php
$arr1 = array( array('Bob', 42), array('Phil', 37), array('Frank', 39) );
        
$arr2 = array( array('Phil', 37), array('Mark', 45) );
        
$arr3 = array_udiff($arr1, $arr2, create_function(
    '$a,$b',
    'return strcmp( implode("", $a), implode("", $b) ); ')
    );
        
print_r($arr3);
?>

Output:

Array
(
    [0] => Array
        (
            [0] => Bob
            [1] => 42
        )
 
    [2] => Array
        (
            [0] => Frank
            [1] => 39
        )
 
)
1

Hope this helps someone
b4301775 at klzlk dot com
пред 7 години
I find it that this is an ideal place to apply the spaceship operator, but it was not used in the examples. 

Here is Example#1 using the spaceship operator in the comparison function. 

    <?php
    // Arrays to compare
    $array1 = array(new stdclass, new stdclass,
                    new stdclass, new stdclass,
                   );

    $array2 = array(
                    new stdclass, new stdclass,
                   );

    // Set some properties for each object
    $array1[0]->width = 11; $array1[0]->height = 3;
    $array1[1]->width = 7;  $array1[1]->height = 1;
    $array1[2]->width = 2;  $array1[2]->height = 9;
    $array1[3]->width = 5;  $array1[3]->height = 7;

    $array2[0]->width = 7;  $array2[0]->height = 5;
    $array2[1]->width = 9;  $array2[1]->height = 2;

    function compare_by_area($a, $b) {
        $areaA = $a->width * $a->height;
        $areaB = $b->width * $b->height;
    
        return $areaA <=> $areaB;
    }

    print_r(array_udiff($array1, $array2, 'compare_by_area'));
    ?>

The output is:
    Array
    (
        [0] => stdClass Object
            (
                [width] => 11
                [height] => 3
            )
    
        [1] => stdClass Object
            (
                [width] => 7
                [height] => 1
            )
    
    )

I find it is pretty awesome you can substitute all of these lines:
    if ($areaA < $areaB) {
        return -1;
    } elseif ($areaA > $areaB) {
        return 1;
    } else {
        return 0;
    }

with just:

    return $areaA <=> $areaB;

Neat!
dmhouse на gmail dot com
21 години пред
Very easy way of achieving a case-insensitive version of array_diff (or indeed array_diff_assoc, array_intersect or any of these types of functions which have a similar function that takes a callback function as one of their parameters):

array_udiff($array1, $array2, 'strcasecmp');

This works because strcasecmp() compares two strings case-insensitively, as compared to the array_diff() which compares two strings by using the == operator, which is case-sensitive.
jared
пред 16 години
Note that php does the string conversion *before* sending the values to the callback function.
aidan на php точка net
21 години пред
This functionality is now implemented in the PEAR package PHP_Compat.

More information about using this function without upgrading your version of PHP can be found on the below link:

http://pear.php.net/package/PHP_Compat
На оваа страница

Автоматски outline од активната документација.

Насловите ќе се појават тука по вчитување.

Попрегледно читање

Примерите, changelog табелите и user notes се визуелно издвоени за да не се губат во долгата содржина.

Брз совет Користи го outline-от Скокни директно на главните секции од активната страница.
Извор Оригиналниот линк останува достапен Кога ти треба целосен upstream context, отвори го PHP.net во нов tab.