douerlin4366 2012-04-27 01:37
浏览 22
已采纳

按顺序重新排序具有重复值的数组

What is the best method to preserve the order of an array while placing duplicate values in order.

Here is the array:

Array
(
    [0] => Array
        (
            [location] => 1320 N Street
        )

    [1] => Array
        (
            [location] => 1316 N St

        )

    [2] => Array
        (
            [location] => 1320 N Street
        )

)

I would like to group duplicate locations so it looks like this:

    Array
(
    [0] => Array
        (
            [location] => 1320 N Street
        )

    [1] => Array
        (
            [location] => 1320 N Street

        )

    [2] => Array
        (
            [location] => 1316 N St
        )

)

My initial thought was to loop through the array and perform an array_search on the location key to get the index a duplicate location, then perform a shift to move the location.

Thanks for your time.

  • 写回答

2条回答 默认 最新

  • dongsechuan0535 2012-04-27 02:13
    关注

    This worked for me:

    $arr = array(
            array("location" => "1320 N Street"),
            array("location" => "1320 N St"),
            array("location" => "1320 N Street"),
    );
    
    $tmp = array();
    $sorted = array();
    foreach ($arr as $k => $v)
    {
            $s = serialize($v);
            if (!isset($tmp[$s]))
            {
                    $tmp[$s] = $k;
                    array_push($sorted, $v);
            } else {
                    $sorted = array_merge(array_slice($sorted, 0, $tmp[$s]+1), array($v), array_slice($sorted, $tmp[$s]+1));
            }
    }
    
    print_r($sorted);
    

    Sample Output:

    Array
    (
        [0] => Array
            (
                [location] => 1320 N Street
            )
    
        [1] => Array
            (
                [location] => 1320 N Street
            )
    
        [2] => Array
            (
                [location] => 1320 N St
            )
    
    )
    

    Edit: Instead of $s = serialize($v); you could also use any key you like, for example $s = $v["location"]; if it's just the location that matters.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改