简体   繁体   English

使多维数组唯一并保持其结构

[英]Make mulitdimensional array unique and keep its structure

I got a multidimensional array that holds multiple session ID's and an array of field data and looks like this: 我有一个多维数组,其中包含多个会话ID和一个字段数据数组,如下所示:

Array 
(
    [102] => Array
        (
            [session_id] => A11.. etc
            [fields] => Array
                (
                    [0] => Array
                        (
                            [date_time] => 2013-03-25 16:28:56
                            [ip_address] => xx.xxx.x.xxx
                            [user_name] => public.static
                            [session_type] => Start
                        )

                    [1] => Array
                        (
                            [date_time] => 2013-03-25 16:28:56
                            [ip_address] => xx.xxx.x.xxx
                            [user_name] => public.static
                            [session_type] => Start
                        )

As you can see, the first 2 field array records hold the same data. 如您所见,前2个字段数组记录保存相同的数据。 So far I have written the following piece of PHP code to make it unique and sort it by date. 到目前为止,我已经编写了以下PHP代码以使其具有唯一性并按日期对其进行排序。

for($i = 0; $i<count($unsortedOutput); $i++) {
    usort($unsortedOutput[$i]['fields'], 'sortFunction');
    $unique[] = array_map('unserialize', array_unique(array_map('serialize', $unsortedOutput[$i]['fields'])));
}

This works but when i print the $unique array, it (as expected) removes the [session_id] and [fields] keys: 这可行,但是当我打印$unique数组时,它(按预期方式)删除了[session_id][fields]键:

Array 
(
    [102] => Array
        (
            [0] => Array
                (
                    [date_time] => 2013-03-25 16:28:56
                    [ip_address] => 94.229.1.233
                    [user_name] => public.static
                    [session_type] => Start
                )

My question is: 我的问题是:

How do I make my multidimensional array unique while keeping the whole structure. 如何在保持整个结构的同时使多维数组唯一。 I feel I'm close, but can't figure out the rest. 我觉得我已经接近了,但无法弄清其余的一切。

As an alternative, you could also use foreach with & reference to each copy to make changes: 或者,您也可以将foreach&引用结合使用以进行每个更改:

foreach($unsortedOutput as &$o) {
    usort($o['fields'], 'sortFunction');
    $o['fields'] = array_map('unserialize', array_unique(array_map('serialize', $o['fields'])));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM