Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I'm running hundreds of curl operations in parallel to my own API, the response array that I get is out of order ( the reason being that the first one to finish gets added to the response array first). I need to sort these back so they correspond to the input array, in order to do that I have already written a function as shown below, I'm interested if there is a more efficient way to do this or not.

Note : The sample shows what I mean, however the input array is usually more than 100 elements long.

Sample Input :

$input = array (
   'http://www.yandex.ru',
   'http://www.mail.ru',
   'http://www.google.com'
)

Response :

$response = array (
    array('http://www.mail.ru', 200, 'some other string'),
    array('http://www.yandex.ru', 200, 'some string'),
    array('http://www.google.com', 200, 'yet another string')
)  

Function :

function re_order($original, $scrambled) {
    foreach ($scrambled as $url_response) {
       $key = array_search($url_response[0],$original);
       $result[$key] = $url_response;
    }
    ksort($result);
    return $result;
}

Resulting array after calling the function (i.e. desired result).

$result = array (
    array('http://www.yandex.ru', 200, 'some string'),
    array('http://www.mail.ru', 200, 'some other string'),
    array('http://www.google.com', 200, 'yet another string')
)  
share|improve this question
3  
Do the URLs in the input and response actually match exactly? If so, you could key the response array by the URL and stop there without having to do a sort. Since your input already is already in order, you can loop over it, get the URL key, then use that to access the response array. –  Corbin Oct 25 at 4:58
    
Why you want to sort it? As you say, requests are done parallel, and you have host in result array. –  Styx Nov 7 at 20:12
    
@Styx, well the URL is only there in the result array to see what result I'm getting ideally I don't need it or the 200 there. Since I wrote this I've added a new function to my parallel curl that carries the original key whilst processing, then sorts out the result array before returning it. (results can come from either file cache, or from curl requests, and can be files or web pages) –  user3510209 Nov 9 at 14:04
    
If you don't need url (input array), then why are you need sorted result? I would do this like @Corbin said. No sorting. –  Styx Nov 9 at 18:17

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.