关联阵列排序

时间:2016-10-21 06:53:26

标签: php arrays sorting

我有如下的数组。我需要通过匹配的大多数标签对数组进行排序。

[0] =>[ 
     [id]=>1,
     [tags]=>Apple,Banana,Mango
    ],
[1] =>[ 
     [id]=>2,
     [tags]=>Apple,Mango,Banana,Orange
    ],
[2] =>[ 
     [id]=>3,
     [tags]=>Mango,Orange
    ],,
[3] =>[ 
     [id]=>4,
     [tags]=>Blackberry,Orange
    ],
[4] =>[ 
     [id]=>5,
     [tags]=>Orange,Blackberry,Banana
    ]

我有一串标签来排序数组。

$tags_str = "Mango,Banana,Orange".  // dynamic string (no. of tags not fix)

数组应按照匹配的标签的顺序排序。

预期产出:

[0] =>[ 
      [id]=>2,
      [tags]=>Apple,Mango,Banana,Orange   // 3 tags matched
     ],
[1] =>[ 
     [id]=>1,
     [tags]=>Apple,Banana,Mango          // 2 tags matched
    ],
[2] =>[ 
     [id]=>3,
     [tags]=>Mango,Orange                // 2 tags matched
    ],
[3] =>[ 
     [id]=>5,
     [tags]=>Orange,Blackberry,Banana   // 2 tags matched
    ],
[4] =>[ 
     [id]=>4,
     [tags]=>Blackberry,Orange          // 1 tag matched
    ]

如何在PHP中实现这一点?

1 个答案:

答案 0 :(得分:0)

OP不值得,但可能的解决方案

<?php
error_reporting(E_ALL);
ini_set('display_errors',1);

$toSort = [
     ['id'=>1,'tags'=>'Apple,Banana,Mango']
    ,['id'=>2,'tags'=>'Apple,Mango,Banana,Orange']
    ,['id'=>3,'tags'=>'Mango,Orange']
    ,['id'=>4,'tags'=>'Blackberry,Orange']
    ,['id'=>5,'tags'=>'Orange,Blackberry,Banana']

];

$tags_str = "Mango,Banana,Orange";

$tagSearch = explode(',',$tags_str);
foreach ($toSort as &$v) {
    $v['m'] = count(array_intersect($tagSearch,explode(',',$v['tags'])));
}

uasort($toSort,function ($a,$b){
    return $b['m']-$a['m'];
});

print_r($toSort);