Search code examples
phparrayssortinghyperlinkinnerhtml

Sort array of hyperlinks by inner HTML


I have an array that is like this:

array(6) { [0]=> string(116) "A" [1]=> string(112) "C" [2]=> string(110) "B" [3]=> string(115) "F" [4]=> string(113) "D" [5]=> string(112) "E" }

and which letter represents an Hyperlink, so each letter is:

<a href="link">Letter</a>

I want to sort this array so I have it sorted by its letter/innerHTML

I want to sort this before echoing.

Any help will be appreciated.

Thank you


Solution

  • You can split the links and create new associative array using letter as key and full link as value. Try below code.

    $links=['<a href="link">D</a>','<a href="link">B</a>','<a href="link">C</a>','<a href="link">A</a>'];
        $new_links=[];
        foreach($links as $link){
            $array_1= explode(">",$link);
            $array_2 = explode("<",$array_1[1]);    
            $new_links[$array_2[0]]=$link;
        }
         ksort($new_links);