简体   繁体   中英

Finding specific key and return value in a multidimentional array

Consider the array below:

//$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
        )
)

I have another array like this:

//$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
                (
                )
        )
)

So I have to read the participants keys in the second array, and then find the name from first array and add it to the member of the second array.

I am trying the code below but I aint got any success so far:

$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?  
    }                          
}

given that the two arrays exist above this block as $schedules and $allmembers , the following should work.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM