1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Which php array function for returning array1 items, if their keys are values in array2

Discussion in 'XenForo Development Discussions' started by Marcus, Aug 1, 2015.

  1. Marcus

    Marcus Well-Known Member

    I want to return only full items from array1, when These according keys are values in array2. In the example below I want to return

    PHP:
    [5] = {
    user_id 5
    username 
    wolf
    mail 
    wolf@mail.com}
    These are the two Arrays:

    PHP:
    array1: [5] = {
    user_id 5
    username 
    wolf
    mail 
    wolf@mail.com},
    [
    9] = {
    user_id 9
    username 
    bear
    mail 
    bear@mail.com}
    PHP:
    array2: Array(2,5)
    Currently I just run a Loop, but would prefer a simple php function. Something like array_intersect_key($array1,$array2)
     
  2. katsulynx

    katsulynx Well-Known Member

    PHP:
    array_intersect_key($array1array_flip($array2))
    Returns
    Code:
    array(1) {
      [5]=>
      array(3) {
        ["user_id"]=>
        int(5)
        ["username"]=>
        string(4) "wolf"
        ["mail"]=>
        string(13) "wolf@mail.com"
      }
    }
    for the following arrays:
    PHP:
    $array1 = array(
                
    => array(
                        
    'user_id' => 5,
                        
    'username' => 'wolf',
                        
    'mail' => 'wolf@mail.com'
                        
    ),
                
    => array(
                        
    'user_id' => 9,
                        
    'username' => 'bear',
                        
    'mail' => 'bear@mail.com'
                        
    )
            );
    $array2 = array(2,5);
    Seems to be what you need.
     
    Marcus likes this.
  3. Marcus

    Marcus Well-Known Member

    Outstanding, thanks!
     
  4. Marcus

    Marcus Well-Known Member

    I have updated my addon, replacing existing logic with phps internal function array_intersect_key:

    Email Notification of ACP Log Errors [Update 1.1]
     

Share This Page