在数组中查找值并在PHP中获取ID

在数组中查找值并在PHP中获取ID

本文介绍了在数组中查找值并在PHP中获取ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个具有不同结构(维度)的数组,我需要在$ second中找到$ first的值(post_name),然后从$ second中获取ID,以创建一个具有$ first和相应的post_name的唯一数组ID建立于$ second.我希望我足够清楚...

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

        )

推荐答案

只需尝试:

$keys = array_map(function ($post) {
  return $post->ID;
}, array_filter($second, function ($post) use ($first) {
  return in_array($post->post_name, $first);
}));

输出:

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);
});

这篇关于在数组中查找值并在PHP中获取ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 22:59