根据某些值排序网址[关闭]

根据某些值排序网址[关闭]

问题描述:

I have array of urls stored. Every url has some format. I need to sort the urls array. Like

https://s3.amazonaws.com/photos/1358086239.jpg?response-content-type=image%2Fjpeg&AWSAccessKeyId=AKIAI2U3TRTNGXNCQHYQ&Expires=1359636889&Signature=l9GnekYT0wK9AznkPWWjBuCRgBY%3D
https://s3.amazonaws.com/photos/1358066630.jpg?response-content-type=image%2Fjpeg&AWSAccessKeyId=AKIAI2U3TRTNGXNCQHYQ&Expires=1359636889&Signature=l9GnekYT0wK9AznkPWWjBuCRgBY%3D

These urls are reutned by amazon S3 PHP SDK get_object_url method.

I have 1000 of these urls but i want to sort these urls based on 1358086239.jpg value this value is everytime an integer value and i want to sort urls in Asc order based on this value.

How can i sort these urls array. i tried using php builtin function ksort() But it did not helped.

Try this (fixed):

$urls = array(
'https://s3.amazonaws.com/photos/1358086239.jpg?response-content-type=image%2Fjpeg&AWSAccessKeyId=AKIAI2U3TRTNGXNCQHYQ&Expires=1359636889&Signature=l9GnekYT0wK9AznkPWWjBuCRgBY%3D',
'https://s3.amazonaws.com/photos/1358066630.jpg?response-content-type=image%2Fjpeg&AWSAccessKeyId=AKIAI2U3TRTNGXNCQHYQ&Expires=1359636889&Signature=l9GnekYT0wK9AznkPWWjBuCRgBY%3D',
);


$list = array();
foreach ($urls as $v) {
   $tmp = explode('https://s3.amazonaws.com/photos/', $v);
   $tmp = explode('.jpg?response-content', $tmp[1]);

   $list[$tmp[0]] = $v;
} 

ksort($list);

var_dump($list);

Try to loop through the URLs and assign each one of them into the array, where key would be your number in a file name. Then simply sort it by keys and... you're done!

What you need is:

sed 's/photos\/\([0-9]+.jpg\)/\1/' | sort would give the file names in order. A grep -f with that as first input and URLs as second would produce your desired output.

Well, something like this...

usort($array, function($a, $b) {
  $aKey = substr($a, 33, 10);
  $bKey = substr($b, 33, 10);
  return $aKey < $bKey;
}
//$array is sorted now

<?php
$url_array  = array('https://s3.amazonaws.com/photos/1358086239.jpg?response-content-type=image%2Fjpeg&AWSAccessKeyId=AKIAI2U3TRTNGXNCQHYQ&Expires=1359636889&Signature=l9GnekYT0wK9AznkPWWjBuCRgBY%3D', 'https://s3.amazonaws.com/photos/1358066630.jpg?response-content-type=image%2Fjpeg&AWSAccessKeyId=AKIAI2U3TRTNGXNCQHYQ&Expires=1359636889&Signature=l9GnekYT0wK9AznkPWWjBuCRgBY%3D');
$res_aray = array();
foreach($url_array as $val){
   preg_match('/photos\/(?P<numb>\d+)\.jpg/', $val, $matches);   
   $res_aray[$matches['numb']] = $val;
}
ksort($res_aray);
print_r($res_aray);

?>