在多维数组中查找特定键和返回值

时间:2013-08-08 22:46:07

标签: php mysql arrays

考虑下面的数组:

//$allmembers
Array
(
    [0] => Array
        (
            [id] => 7
            [name] => John Smith
        )
    [1] => Array
        (
            [id] => 8
            [name] => John Skeet
        )
    [2] => Array
        (
            [id] => 9
            [name] => Chuck Norris
        )
    [3] => Array
        (
            [id] => 10
            [name] => Bruce Lee
        )
)

我有另一个这样的数组:

//$schedules
Array
(
    [0] => Array
        (
            [id] => 24
            [title] => DAMN DAMN DAMN!
            [description] => 
            [room] => 5022
            [start] => 1362783300
            [end] => 1362783300
            [participants] => 7,8
            [members] => Array
                (
                )
        )
    [1] => Array
        (
            [id] => 22
            [title] => blah blah
            [description] => 
            [room] => 5022
            [start] => 1365024780
            [end] => 1365026280
            [participants] => 9,10
            [members] => Array
                (
                )
        )
)

所以我必须读取第二个数组中的参与者键,然后从第一个数组中找到名称并将其添加到第二个数组的成员

我正在尝试下面的代码,但到目前为止我没有取得任何成功:

$allmembers = $_DB->Query("SELECT id,name FROM members");

for($i = 0; $i < count($schedules); $i++)
{
    $schedules[$i]["members"] = array() ;
    $mems = array();        

    $mems = explode(',', $schedules[$i]["participants"]);                                               

    for($j = 0; $j < count($mems); $j++)
    {
        //How to search the first array?  
    }                          
}

1 个答案:

答案 0 :(得分:1)

如果两个数组在此块上方作为$schedules$allmembers存在,则以下内容应该有效。

foreach($schedules as &$event)
{
    $participants = array_flip(explode(',', $event['participants']));

    $addThese = array();
    foreach($allmembers as $member)
    {
        if (isset($participants[$member['id']]))
            $addThese[] = $member;
    }

    $event['participants'] = $addThese;
} unset($event);

print_r($schedules);