PHP-对象数组相交并合并,保持对象完整

时间:2018-10-01 16:26:15

标签: php arrays object multidimensional-array

我有一个多维数组,其中包含从DB返回的对象数组:

Array
(
    [0] => Array
        (
            [0] => stdClass Object
                (
                    [image_id] => 1
                )

            [1] => stdClass Object
                (
                    [image_id] => 5
                )

            [2] => stdClass Object
                (
                    [image_id] => 6
                )

            [3] => stdClass Object
                (
                    [image_id] => 7
                )
        )
    [1] => Array
        (
            [0] => stdClass Object
                (
                    [image_id] => 5
                )

            [1] => stdClass Object
                (
                    [image_id] => 6
                )
        )
    [2] => Array
        (
            [0] => stdClass Object
                (
                    [image_id] => 5
                )
        )
)

我需要能够与嵌套数组相交,以仅保留所有数组集中存在的image_id。因此,在上面的示例中,这只会返回image_id = 5。

我需要将其保留为类似于以下内容的对象数组:

Array
(
    [0] => stdClass Object
        (
            [image_id] => 5
        )
)

我尝试了其他帖子中的一些代码。这类似于php - array intersect and merge,但是他们正在尝试删除重复的邮件,这种情况略有不同。

我见过的所有比较数组的情况都是已知数组的地方(即$ arr1,$ arr2)。用户的情况可能是任意长度的多数组。

任何帮助都会很感激,因为他们一直在努力寻找解决方案。

预先感谢

1 个答案:

答案 0 :(得分:1)

首先,我们需要遍历image_ids并获取重复的图像。然后,我们需要重建所需的结构。

<?php

$test_array = [
    [
        (object)['image_id' => 1],
        (object)['image_id' => 2],
        (object)['image_id' => 3],
        (object)['image_id' => 4],
        (object)['image_id' => 5],
    ],
    [
        (object)['image_id' => 2],
        (object)['image_id' => 3],
    ],
    [
        (object)['image_id' => 1],
        (object)['image_id' => 2],
        (object)['image_id' => 3],
    ]
];


$first_iteration = true;
$duplicates = [];

foreach ($test_array as $outer_key => $outer_array) {

    $current_array_values = [];
    foreach ($outer_array as $image_id) {
        $current_array_values[] = $image_id->image_id;
    }

    // If first iteration, then we will have
    // no IDs to check against.
    if ($first_iteration) {
        $duplicates = $current_array_values;
        $first_iteration = false;
    } else {
        $duplicates = array_intersect($duplicates, $current_array_values);
    }   
}

$output = [];
foreach($duplicates as $duplicate) {
    $output[] = (object)['image_id' => $duplicate];
}

$ output:

array(2) {
  [0]=>
  object(stdClass)#11 (1) {
    ["image_id"]=>
    int(2)
  }
  [1]=>
  object(stdClass)#12 (1) {
    ["image_id"]=>
    int(3)
  }
}

让我知道您是否有任何问题。