Find value in array and get ID in PHP

痞子三分冷 提交于 2019-12-25 09:14:12

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!