new_php_developer new_php_developer - 5 months ago 70
PHP Question

array unique and merge value in an array of objects

I have one big array and I want to make it unique on doc_id and merge roleid

Array
(
[0] => stdClass Object
(
[title] => Test ÆØÅ
[doc_id] => 279
[mid] =>
[type] => 3
[label] =>
[roleid] => 76, 276
)

[1] => stdClass Object
(
[title] => Test ÆØÅ
[doc_id] => 279
[mid] =>
[type] => 3
[label] =>
[roleid] => 76, 276
)

[2] => stdClass Object
(
[title] => NVD AS
[doc_id] => 415
[mid] =>
[type] => 3
[label] =>
[roleid] => 2
)

[3] => stdClass Object
(
[title] => NVD AS
[doc_id] => 415
[mid] =>
[type] => 3
[label] =>
[roleid] => 76, 276
)

[4] => stdClass Object
(
[title] => Test for SN
[doc_id] => 506
[mid] =>
[type] => 3
[label] =>
[roleid] => 76, 276
)

[5] => stdClass Object
(
[title] => Test for SN
[doc_id] => 506
[mid] =>
[type] => 3
[label] =>
[roleid] => 6
)


Just to make it unique I am using below code

foreach ($arry as $val) {
$newArr[$arry ->doc_id] = $val;
}
$result = array_values($newArr);


I am able to get unique document but I lost roleid, I need to merge roleid with doc_id
it should be

Array
(
[0] => stdClass Object
(
[title] => Test ÆØÅ
[doc_id] => 279
[mid] =>
[type] => 3
[label] =>
[roleid] => 76, 276
)

[1] => stdClass Object
(
[title] => NVD AS
[doc_id] => 415
[mid] =>
[type] => 3
[label] =>
[roleid] => 2,76, 276
)

[2] => stdClass Object
(
[title] => Test for SN
[doc_id] => 506
[mid] =>
[type] => 3
[label] =>
[roleid] => 6,76, 276
)
Can anyone help in this


Thanks in advance

Answer

Your current format of roleid is not in the best format for processing. If you change it to array you can do something similar to this:

$item1 = new stdClass();
$item1->doc_id = 279;
$item1->role_id = '76, 276, 3';

$item2 = new stdClass();
$item2->doc_id = 279;
$item2->role_id = '1, 44, 76';

$item3 = new stdClass();
$item3->doc_id = 279;
$item3->role_id = '8, 44, 1';

$data = [$item1, $item2, $item3];

$result = [];
foreach ($data as $item) {
    if (isset($result[$item->doc_id])) {
        $existingIds = explode(', ', $result[$item->doc_id]->role_id);
        $newIds = explode(', ', $item->role_id);

        $result[$item->doc_id]->role_id = implode(', ', array_unique(array_merge(
            $existingIds,
            $newIds
        )));

        continue;
    }

    $result[$item->doc_id] = $item;
}


print_r($result);

With the result:

Array
(
    [279] => stdClass Object
        (
            [doc_id] => 279
            [role_id] => 76, 276, 3, 1, 44, 8
        )

)
Comments