Kumar Vivek
Kumar Vivek

Reputation: 21

How to remove array if all keys acquired by another array in multidimensional array PHP

can you please help me out in this. What will be the function to remove 4th and 5th array in PHP.

Array
(
    [0] => Array
        (
            [10] => 98
            [11] => 1
            [433438] => 8
        )

    [1] => Array
        (
            [10] => 98
            [11] => 1
            [433438] => 1
        )

    [2] => Array
        (
            [13] => 98
            [11] => 2
            [433438] => 8
        )

    [3] => Array
        (
            [14] => 98
            [11] => 2
            [433438] => 1
        )

    [4] => Array
        (
            [10] => 18
            [11] => 1
        )

    [5] => Array
        (
            [14] => 18
            [11] => 2
        )

)

Thanks in Advance.

Upvotes: 0

Views: 51

Answers (2)

Ersoy
Ersoy

Reputation: 9604

$base = [
    [10 => 98, 11 => 1, 433438 => 8],
    [10 => 98, 11 => 1, 433438 => 1],
    [13 => 98, 11 => 2, 433438 => 8],
    [14 => 98, 11 => 2, 433438 => 1],
    [10 => 18, 11 => 1],
    [14 => 18, 11 => 2],
];

$invalid = [];

for ($i = 0; $i <= count($base) - 1; $i++) {
    for ($j = 0; $j <= count($base) - 1; $j++) {
        $refCount = count($base[$j]);
        $interSectCount = count(array_intersect(array_keys($base[$i]), array_keys($base[$j])));
        if (count($base[$i]) !== $refCount && $interSectCount === $refCount) {
            $invalid[] = $j;
        }
    }
}

foreach ($invalid as $item) {
    unset($base[$item]);
}

Upvotes: 1

Kunal Raut
Kunal Raut

Reputation: 2584

You can use array_pop() function which eliminates the last element of the array but if you use it two times you will get the desired result as

<?php
$data  = [
    1 => [1,2],
    2 => [1,3],
    3 => [1,4]
];
$value = array_pop($data);
$value = array_pop($data);
?>

Output

Array
(
    [1] => Array
        (
            [0] => 1
            [1] => 2
        )

)

Upvotes: 0

Related Questions