问题
I've 2 arrays with different structures (dimension), i need to find values (post_name) of $first in $second and then get ID from $second in order to create a unique array with post_name of $first and corresponding ID founded in $second. i hope i'm clear enough...
I need to keep the same order of first Thanks
$first= Array
(
[0] => 'lundi-5',
[1] => 'mardi-5',
[2] => 'lundi-1',
[3] => 'mardi-1',
);
$second=Array
(
[0] => WP_Post Object
(
[ID] => 2878
[post_name] => lundi-1
)
[1] => WP_Post Object
(
[ID] => 3180
[post_name] => mardi-1
)
[2] => WP_Post Object
(
[ID] => 3181
[post_name] => lundi-5
)
[3] => WP_Post Object
(
[ID] => 3182
[post_name] => mardi-5
)
回答1:
Just try with:
$keys = array_map(function ($post) {
return $post->ID;
}, array_filter($second, function ($post) use ($first) {
return in_array($post->post_name, $first);
}));
Output:
array(2) {
[2]=>
int(3181)
[3]=>
int(3182)
}
To return whole objects, use:
$posts = array_filter($second, function ($post) use ($first) {
return in_array($post->post_name, $first);
});
来源:https://stackoverflow.com/questions/39250988/find-value-in-array-and-get-id-in-php