【问题标题】:Find value in array and get ID in PHP在数组中查找值并在 PHP 中获取 ID
【发布时间】:2017-01-08 03:00:47
【问题描述】:

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

我需要保持与 first 相同的顺序 谢谢

$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

        )

【问题讨论】:

    标签: php arrays search


    【解决方案1】:

    试试看:

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

    要返回整个对象,请使用:

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

    【讨论】:

    • 谢谢!!!但对不起,我不明白数组结构......我怎么能得到这样的数组:Array([0] => Array([name] =>lundi-5 [id] => 3181)[ 1] => 数组([名称] => mardi-5 [id] => 3182))
    • 啊它似乎可以工作,但返回的结果似乎不像 $first 那样排序
    • 请问@hsz你有什么想法吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-08
    • 1970-01-01
    • 2019-09-20
    • 2014-12-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多