我有一个大数组,我想在doc_id和merge role
上使它成为唯一的 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
)
只是为了让它独一无二,我正在使用下面的代码
foreach ($arry as $val) {
$newArr[$arry ->doc_id] = $val;
}
$result = array_values($newArr);
我能够获得唯一的文档但是我丢失了roleid,我需要将roleid与doc_id合并 它应该是
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
提前致谢
答案 0 :(得分:0)
您可以尝试使用array_merge_recursive()
函数合并数组。
$mergedArray = array_merge_recursive($arr1, $arr2);
您正在丢失值,因为您会覆盖它们。你应该使用两个循环。
foreach ($array as $key => $value) {
foreach ($value as $subkey => $subvalue) {
$newArray[$value->doc_id][$subkey] = $subvalue;
}
}
我似乎无法找到上述原因不适合你的原因。虽然我会给你写另一个解决方案:
$newaArray = array();
foreach ($array as $value) {
if (!is_array($newArray[$value->doc_id])) {
$newArray[$value->doc_id] = array();
}
$newArray[$value->doc_id] = array_merge($newArray[$value->doc_id], $value);
}
答案 1 :(得分:0)
您当前的roleid
格式不是最佳处理格式。如果将其更改为数组,则可以执行与此类似的操作:
$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);
结果:
Array
(
[279] => stdClass Object
(
[doc_id] => 279
[role_id] => 76, 276, 3, 1, 44, 8
)
)