Get a subset of an array based on an array of keys

后端 未结 3 664
臣服心动
臣服心动 2020-12-07 01:14

I wrote this function to get a subset of an array. Does php have a built in function for this. I can\'t find one in the docs. Seems like a waste if I\'m reinventing the whee

3条回答
  •  孤街浪徒
    2020-12-07 01:31

    There is no direct function I think in PHP to get a subset from an array1 with compare to another array2 where the values are the list of key name which we fetch.

    Like: array_only($array1, 'field1','field2');

    But this way can be achieved the same.

     'John', 'lastname' => 'Smith', 'DOB' => '2000-10-10', 'country' => 'Ireland' ];
    
    $subset = array_intersect_key( $associative_array, array_flip( [ 'lastname', 'country' ] ) );
    
    print_r( $subset );
    
    // Outputs...
    // Array ( [lastname] => Smith [country] => Ireland );
    

提交回复
热议问题