Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP and 2 multidimensional array compare based on two key values

I have two multidimensional arrays like this:

$original = Array (
[0] => Array
    (
        [time] => 1364690340
        [memberid] => 90
        [type] => single
    )

[1] => Array
    (
        [time] => 1364690341
        [memberid] => 92
        [type] => fixed
    )

[2] => Array
    (
        [time] => 1364690342
        [memberid] => 96
        [type] => single
    )
)

and second one like this

$new = Array (
[0] => Array
    (
        [time] => 1364825750
        [memberid] => 90
        [type] => single
    )

[1] => Array
    (
        [time] => 1364825751
        [memberid] => 92
        [type] => single
    )

[2] => Array
    (
        [time] => 1364825752
        [memberid] => 96
        [type] => single
    )

[3] => Array
    (
        [time] => 1364825753
        [memberid] => 111
        [type] => single
    )
)

My problem is: I want to search $original array for matches based on memberid and type keys and if memberid and type ARE NOT the same -> I want to remove that array from $original array. So in this case I want to keep [0] Array and [2] Array as in $new array I have same memberid and same type as in original, but I would want to remove [1] Array as memberid is the same, but type is different. So my final $original array will look like this:

$original = Array (
[0] => Array
    (
        [time] => 1364690340
        [memberid] => 90
        [type] => single
    )

[1] => Array
    (
        [time] => 1364690342
        [memberid] => 96
        [type] => single
    )
)
like image 758
Peter Avatar asked Nov 12 '22 08:11

Peter


1 Answers

Here you go, just tested it and it works as expected.

// Presuming your two arrays are still called $new & $original
$original = array(); // your data
$new = array(); // your data

$newArray = array();
foreach($original AS $key => $val){
    $newArray[$val['memberid'] . '-' . $val['type']] = $val;
}

$original = array();
foreach($new AS $key => $val){
    if(isset($newArray[$val['memberid'] . '-' . $val['type']])){
        $original[] = $newArray[$val['memberid'] . '-' . $val['type']];
    }
}

print_r($original);
like image 186
Adrian Avatar answered Nov 14 '22 21:11

Adrian