简体   繁体   中英

PHP Get values from associative array based on list of matched keys

I'm trying to do the following:

  1. Grab key/value pairs from an array $post_data ...

  2. Only where the key matches a provided list $my_fields ...

  3. And create a new array with only the matched data.

For example, from $post_data I'd like to grab the key/value pairs for first_name , last_name , and title while ignoring user_email . I'd then like to create a new array named $clean_data with these key/value pairs.

Below is my failed attempt at looping through the $post_data array and pulling out the matches based on the $my_fields array.

// These are the fields I'd like to get from the $post_data array
$my_fields = array(
    'first_name',
    'last_name', 
    'title'
); 

// This is the raw data. I do not need the 'user_email' key/value pair.
$post_data = array(
    'first_name' => 'foo',
    'last_name'  => 'bar',
    'title'      => 'Doctor',
    'user_email' => 'fb@gmail.com'
);

$clean_data = array();

$counter == 0;
foreach ($post_data as $key => $value) 
{
    if (array_key_exists($my_fields[$counter], $post_data)) 
    {
        $clean_data[$key] = $value;
    }
    $counter++;
}

// Incorrectly returns the following: (Missing the first_name field) 
// Array
// (
//     [last_name] => bar
//     [title] => Doctor
// )

No looping needed - you can have it all done in one line if you want. Here is the magic function:

And if you don't want to modify your $my_fields array you can use array_flip()

And for further reading all other fun you can have with arrays.

Now that MARKY chose the answer, here is the example how it could be done by differently:

$my_fields = array(
    'first_name',
    'last_name', 
    'title'
); 

$post_data = array(
    'first_name' => 'foo',
    'last_name'  => 'bar',
    'title'      => 'Doctor',
    'user_email' => 'fb@gmail.com'
);

$clean_data = array_intersect_key($post_data, array_flip($my_fields));

this produces

array (
    'first_name' => 'foo',
    'last_name'  => 'bar',
    'title'      => 'Doctor',
)  

You should use this.

foreach($post_data as $key=>$value){
    if(in_array($key,$my_fields)){
    $clean_data[$key]=$value;
    }
}
print_r($clean_data);

You are trying in the right direction, just the matching of key in the array has to be in a different way.

you can replace it with your foreach section no counter needed

foreach ($post_data as $key => $value) 
{
    if (in_array($key,$my_fields)) 
    {
        $clean_data[$key] = $value;
    }
}

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