I’m trying to merge 2 arrays in PHP and then sort them.
I’m pulling data from WordPress database ( tags and categories ) and I need to merge them and sort them properly.
Code looks similar to this:
$categories = [
'<a>WordPress Tips</a>',
'<a>SEO Tips'</a>,
'<a>Development Tips</a>'
];
$tags = [
'<a>WordPress</a>',
'<a>SEO'</a>,
'<a>Development</a>'
];
$taxonomies = array_merge($categories, $tags);
sort($taxonomies);
Since I need to loop through $taxonomies array and print them with anchors included ( every one of those must have a valid URL to itself ), I don’t get a proper sorting result. However, as soon as I ‘strip out’ all the tags around these items, sorting works as it should, but I don’t get URLs that I need, only string / text.
Could someone suggest a better sorting algorithm which would sort these items properly with html elements included around them? Thanks!
2
Answers
Since you mentioned that the tags stripped version works, a simple way might be to use them as the keys in the sort. Something like this, for instance :
Which will give the sorted array and you can just use the values in there. Maybe there’s better options but this comes to mind off the top of my head..
EDIT : uasort with a comparision function that actually compares the stripped versions might be better, after looking at other answers here.
You need to do custom comaprision to make it work using usort() and strip_tags()
Output:-https://eval.in/934071