2

I was just wondering if php had built in functions to filter an array based on the key of another array?

array 1 - is a list of all users and their basic info

array 2 - contains a meeting schedule with the users id's

e.g.

array 1 [0]([user_id], [name], [age], [contact]), 
        [1]([user_id], [name], [age], [contact])
        etc.

array 2 [0]([user_id], [time], [date], [place])
        [1]([user_id], [time], [date], [place])

Is there a way to filter array 1 so that it only contains the rows that correspond to the [user_id] in array 2.

I understand that I could use loops and custom functions to achieve this however, I just wanted to see if there was a simple way.

Thanks

4

2 回答 2

2
array_intersect_key($array1, $array2)

PHP Manual

code:

$array1 = array('user1'=> array('name'=>'name1','age' => 'age1'),
                'user2'=> array('name'=>'name2','age' => 'age2'),
                'user3'=> array('name'=>'name3','age' => 'age3'));

//array with key to search for
$array2 = array('user2'=> array('time'=>'time2','date' => 'date2'));     
echo '<pre>';
print_r(array_intersect_key($array1,$array2));
echo '</pre>';

o/p:

    Array
(
    [user2] => Array
        (
            [name] => name2
            [age] => age2
        )

)

edit:

Ah got your problem. If you want to manipulate your given array as per the above structure and then apply array_intersect_key(), you can do this:

function compare($key1,$key2){
    global $array1,$array2;

    if($array1[$key1]['userid'] == $array2[$key2]['userid'])
        return 0;
    if($array1[$key1]['userid'] > $array2[$key2]['userid'])
        return 1;
    else
        return -1;
}

$array1 = array(array('userid'=>'user1','name'=>'name1','age' => 'age1'),
                array('userid'=>'user2','name'=>'name2','age' => 'age2'),
                array('userid'=>'user3','name'=>'name3','age' => 'age3'));

//array with key to search for
$array2 = array(array('userid'=>'user2','time'=>'time2','date' => 'date2'));     

echo '<pre>';
print_r(array_intersect_ukey($array1,$array2,'compare'));
echo '</pre>';

o/p:
====
Array
(
    [1] => Array
        (
            [userid] => user2
            [name] => name2
            [age] => age2
        )

)
于 2013-04-10T17:56:35.337 回答
1

I've decided it's much easier to just use 2 loops.

The first one to create an array of the [user_id]'s and the second one to use in_array like, so:

$user_id = array();
foreach($users as $id){
    $user_id[]= $id['user_id'];
}
$names = array();
foreach ($schedule as $name){
    if(in_array($name['id'], $user_id)) $names[] = $name;
}

Too simple to bother looking for a php function.

于 2013-04-11T07:53:40.883 回答