0

I have two arrays like

Array
(
    [0] => Array
        (
            [id] => 1
            [controller] => users
            [action] => index
        )

    [1] => Array
        (
            [id] => 1
            [controller] => users
            [action] => 
        )

    [2] => Array
        (
            [id] => 1
            [controller] => users
            [action] => login
        )

)
Array
(
    [0] => Array
        (
            [id] => 1
            [controller] => users
            [action] => index
        )

    [1] => Array
        (
            [id] => 1
            [controller] => users
            [action] => 
        )

    [2] => Array
        (
            [id] => 1
            [controller] => users
            [action] => logout
        )

)

I want to remove complete nested array from 1st array if a match is found in 2nd array (Based on keys ['controller'] &&['action']). So in the first array only the 3rd [2] array is unique.

The output should be like :

Array
    (
        [0] => Array
            (
                [id] => 1
                [controller] => users
                [action] => login
            )
    )

Please Note Please note that the 2nd array doesn't necessary to be in same order as first. As opposed in my question where the first two arrays of each array are identical.

What i have tried is :

$result = array();

for($i=0; $i < count($a); $i++)
{
    $result[] = array_diff($a[$i], $b[$i]);
}

print_r($result); // This doesn't give required output. It removes every thing and return like 


Array
    (
        [0] => Array
            (
            )

        [1] => Array
            (
            )

        [2] => Array
            (
                [action] => login
            )

    )
Raheel
  • 8,716
  • 9
  • 60
  • 102

3 Answers3

1

Have a look at this answer. I think it'll do exactly what you need it to.

Community
  • 1
  • 1
0

There are numerous ways you could go about this. Here's one that I think would be pretty simple.

First up, setup a new array based on $a, indexing it by the controller and action attributes.

$final = array();
foreach($a AS $item) {
    $final[$item['controller'] . $item['action']] = $item;
}

Now you can loop through the second array, removing any matching items.

foreach($b AS $item) {
    unset($final[$item['controller'] . $item['action']]);
}

Now $final should be the array you want.

Working example: http://3v4l.org/JtUkN

JoeCoder
  • 870
  • 5
  • 4
0

Here is my own working solution

for($i=0; $i < count($data); $i++)
    {
        foreach($this->existing_data as $v)
        {
            if( ($v['controller'] == $data[$i]['controller']) && ($v['action'] == $data[$i]['action']) )
            {
                unset($data[$i]);
                break;
            }
        }

    }
Raheel
  • 8,716
  • 9
  • 60
  • 102