简体   繁体   中英

elegant way to update many-to-many relationship

Currently to update many-to-many relationship I am iterating old list and current list to find which items were changed. For example:

$new = array('apple', 'orange');
$old = array('banana');

$added = array();

foreach($new as $v)
{
    if(!in_array($v, $old))
    {
        $added[] = $v;
    }        
}


$removed = array();

foreach($old as $v)
{
    if(!in_array($v, $new))
    {
        $removed[] = $v;
    }
}

// update them

What would be more elegant(and shorter) way to implement same thing?

Use array_diff

$added = array_diff($new, $old);
$removed = array_diff($old, $new);

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