Shi*_*ina 9 php arrays multidimensional-array
我想从中删除重复值,如您所见list_title.我知道有几个问题和答案,但他们的解决方案对我不起作用.
这是我尝试过的:
$uniqueArray = array_map("unserialize", array_unique(array_map("serialize", $notify)));
Run Code Online (Sandbox Code Playgroud)
结果:
Array
(
[0] => Array
(
[list_id] => 86
[list_reference] => 130948
[list_title] => Offer: apartment 2+kk
[list_city] => Prague
[list_date] => 2017-03-03 11:20:35
[list_status] => 0
[list_creator] => Company A
[list_price] => 30000
[list_furniture] => ["1","0","0"]
[list_accommodation] => flat
)
[1] => Array
(
[list_id] => 87
[list_reference] => 130947
[list_title] => Offer: apartment 2+kk
[list_date] => 2017-03-03 11:20:35
[list_status] => 0
[list_creator] => Company B
[list_price] => 30000
[list_furniture] => ["1","0","0"]
[list_accommodation] => flat
)
[2] => Array ...
Run Code Online (Sandbox Code Playgroud)
由于标题,预期结果应该是其中之一:
Array
(
[0] => Array
(
[list_id] => 86
[list_reference] => 130948
[list_title] => Offer: apartment 2+kk
[list_city] => Prague
[list_date] => 2017-03-03 11:20:35
[list_status] => 0
[list_creator] => Company A
[list_price] => 30000
[list_furniture] => ["1","0","0"]
[list_accommodation] => flat
)
Run Code Online (Sandbox Code Playgroud)
因此,基本上,您想按'list_title'列删除重复项。假设我们保留该标题的第一次出现。然后,您可以使用几个标准函数来实现此目的:
// Reverse array, so the first occurrence kept.
$data = array_reverse($data);
$result = array_reverse( // Reverse array to the initial order.
array_values( // Get rid of string keys (make array indexed again).
array_combine( // Create array taking keys from column and values from the base array.
array_column($data, 'list_title'),
$data
)
)
);
Run Code Online (Sandbox Code Playgroud)
这是工作演示。
更新:
基于@mickmackusa注释,可以将代码简化为:
$result = array_reverse(array_values(array_column(
array_reverse($data),
null,
'list_title'
)));
Run Code Online (Sandbox Code Playgroud)
在文档中有关column_key参数规格的说明如下:
返回完整的数组或对象也可能为NULL(这与index_key一起用于重新索引数组很有用)。
谢谢大家,有时过度思考会影响常识。
我只是从 MYSQL 查询中解决了它,例如:
GROUP BY list_title ORDER BY list_date
Run Code Online (Sandbox Code Playgroud)