user1294097
user1294097

Reputation: 153

How to sort by ID in url using php and preg_match

I have a php working code where I take an array full of URLs, I use preg_match to obtain all the information within the URL for example a typical url looks like this:

http://photos.com/path=images&user=Ron197&userid=970965&hue=soft

To match the userid I use this within a foreach loop:

preg_match_all('/userid=(.+?)&hue/', $linklong, $userid);
        $userid = $userid[1][0];
        //print_r($userid);

The main array is sorted in alphabetical order with more than 600 urls and it displays just fine like that, but I'm trying to also display the entire list of URLs sorted by userid.

Can anyone help at least get me started I tried using ksort, usort, but I honestly don't get the logic behind it The idea is that linklong would need to be rearranged by userid

Upvotes: 0

Views: 1482

Answers (1)

MatRt
MatRt

Reputation: 3534

First, you should use parse_url to extract your 'query' part. Then, using parse_str, you can separate all parameters.

This allow you to check that your URL has is valid.

Then, if you want to be able to sort the array on any field you want (and not only on the userId) you just have to create a callback function that will take 2 elements of your array and return -1, 0 or 1 respectivelly if the first element is <, =, > than the second one.

Then, to order your array, you just have to call the function usort:

bool usort ( array &$array , callable $cmp_function )

giving your array as first parameter and your callback function as second parameter. This allow you to create any comparision callback you want and order your array like you want.

Note: Take care of the performance.. If your callback do a lot of stuff, the sort will take some time because the callback function is called a lot of time between elements of your array, following a specific sorting algorithm (like the bubbling sort).

An example of a such comparision function:

function compareUrlCustom($u1, $2)
{
    // Parse the 2 URLs
    $urlParts1 = parse_url($u1);
    $urlParts2 = parse_url($u2);

    // Extract and parse the 2 query parts
    $queryParts1 = array();
    $queryParts2 = array();
    parse_str($urlParts1['query'], $queryParts1);
    parse_str($urlParts2['query'], $queryParts2);

    // Return 1, O or -1 as comparision value
    if ($queryParts1['userId'] > $queryParts2['userId'])
        return 1;
    else if ($queryParts2['userId'] > $queryParts1['userId'])
        return -1;
    else
        return 0;
}

And then, you can call the sort of your array with:

$wellSorted = usort($yourArray, compareUrlCustom);

and check $wellSorted to know if the sort operation is a success or not.

Note: you should add some check in the compareUrlCustom function to be sure to have valid URL and eventually throw an exception if its not the case.

Upvotes: 1

Related Questions