gpt4 book ai didi

PHP从数组中删除重复的对象

转载 作者:行者123 更新时间:2023-12-03 22:47:59 24 4
gpt4 key购买 nike

我已经尝试了各种 PHP 逻辑和 PHP 的内置函数来删除重复值,但它不起作用没有出现任何错误,但是如果使用 array_unique() in_array() 我所有的 JQuery 和 CSS 都不起作用删除数组中的重复对象

这就是我如何创建我的 person_row_array在 while 循环中:

$person_row = Person::findByID($pi_claimant_row->person_id);
$person_row_array[] = $person_row;

对象 print_r 如下:
Array
(
[0] => stdClass Object
(
[id] => 12
[flat_no] =>
[house_no] => *
[street] =>
[town] =>
[postcode] => *
[county] =>
)

[1] => stdClass Object
(
[id] => 14
[flat_no] => 2
[house_no] => 33
[street] => Street
[town] => Town
[postcode] => BB
[county] => County
)

[2] => stdClass Object
(
[id] => 14
[flat_no] => 2
[house_no] => 33
[street] => Street
[town] => Town
[postcode] => BB
[county] => County
)

[3] => stdClass Object
(
[id] => 14
[flat_no] => 2
[house_no] => 33
[street] => Street
[town] => Town
[postcode] => BB
[county] => County
)

[4] => stdClass Object
(
[id] => 15
[flat_no] => FN
[house_no] => HN
[street] => Street
[town] => Nelson
[postcode] => PC
[county] => Manchester
)

[5] => stdClass Object
(
[id] => 15
[flat_no] => FN
[house_no] => HN
[street] => Street
[town] => Nelson
[postcode] => PC
[county] => Manchester
)

[6] => stdClass Object
(
[id] => 16
[flat_no] => FN
[house_no] => house
[street] => Manchester Road
[town] => Town
[postcode] => M1 4MK
[county] => County
)

)

我想删除那些重复的,请帮忙,请不要建议我使用 array_unique() 我过去几个小时一直在尝试这个没有工作,但如果你能告诉我任何其他方式或添加对象,如果已经不退出。

请注意,这是假数据,我只想删除那些具有相似 ID 的数组。

此致

最佳答案

试试下面的代码

function my_array_unique($array, $keep_key_assoc = false){
$duplicate_keys = array();
$tmp = array();

foreach ($array as $key => $val){
// convert objects to arrays, in_array() does not support objects
if (is_object($val))
$val = (array)$val;

if (!in_array($val, $tmp))
$tmp[] = $val;
else
$duplicate_keys[] = $key;
}

foreach ($duplicate_keys as $key)
unset($array[$key]);

return $keep_key_assoc ? $array : array_values($array);
}

关于PHP从数组中删除重复的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24558484/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com