Peter
Peter

Reputation: 1296

Fastes way to compare single-dimensional against multidimensional array in PHP

I have a multidimensional array like this:

Array (
[0] => Array
    (
        [time] => 1364685993
        [memberid] => 131
    )

[1] => Array
    (
        [time] => 1364685994
        [memberid] => 133
    )
[2] => Array
    (
        [time] => 1364685995
        [memberid] => 141
    )
)

and a single-dimensional array like this:

Array (
  [0] => 131
  [1] => 141
  [2] => 191
  [3] => 205
)

Now I want to remove all Sub-arrays from multidimensional arrays that DOES NOT contain the memberid value from normal array ?

In this case only Subaray[1] to be removed from multidimensional array as it's 'memberid' key value (133) doesn't show in normal array. Those arrays are actually pretty big, so I am not sure what would be fastest way to do it ?

Upvotes: 0

Views: 984

Answers (4)

Sverri M. Olsen
Sverri M. Olsen

Reputation: 13283

Instead of filtering the database results after the fact you may want to use the single-dimensional array in the database query itself.

We do not know what the query, you are using, looks like, but something along these lines would do it:

// The ids from the file
$use_ids = array(131, 141, 191, 205);

// Create a list for the IN clause
$ids = '(' . implode(',', $use_ids) . ')';

// Create the query
$query = <<< SQL
    SELECT time, memberid
    FROM some_table
    WHERE ...
        AND memberid IN {$ids}
    ORDER BY time
SQL;

// Execute the query, etc.

It is always a good idea to let the SQL handle as much filtering of content as possible.

Upvotes: 0

user1467267
user1467267

Reputation:

Don't have access to development resources at the moment to test but this should work.

foreach($members as $member => $property) {
    if (!in_array($property['member_id'], $id_array)) {
        unset($members[$member]);
    }
}

$id_array is the 1-dimensional matrix (array) you've put in your question.

Upvotes: 1

deceze
deceze

Reputation: 522081

$normalArray = array_flip($normalArray);

$multiDimArray = array_filter($multiDimArray, function ($elem) use ($normalArray) {
    return isset($normalArray[$elem['memberid']]);
});

Requires exactly two iterations, one over each array. Key lookups using $normalArray[$elem['memberId']] are blazingly fast. May have some memory overhead due to the functional nature and copies of arrays, use a traditional loop and unset if that's an issue.

Upvotes: 4

nickb
nickb

Reputation: 59699

First, I would flip the $nomal array to get constant lookup time into the array, like this:

$normal = array_flip( $normal);

Then, you just have to filter the $multidimensional_array by the $normal array with a simple lookup:

$filtered = array_filter( $multidimensional_array, function( $el) use( $normal) {
    return isset( $normal[ $el['member_id'] ]);
});

Upvotes: 3

Related Questions