Online Online - 1 month ago 4
PHP Question

Associate Array Sorting

I have array like below. I need to sort array by most tags matched.

[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
]


I have string of tags to sort array.

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


Array should be sort in desc order of tags matched.

Expected output:

[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
]


How can achieve this in php ?

Answer

OP don't deserve it but, on possible solution

<?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);