0

I have an array that looks like this:

Array
(
    [0] => ripe@hobby.nl 20140827
    [1] => bas@hobby.nl 20130827
    [2] => bas@dikkenberg.net 20140825
    [3] => bas@hobby.nl 20120825
    [4] => ripe@hobby.nl 20140826
)

Now i want to sort this array in php based on the numbers only so ignoring the e-mail adres in the sort process.

nl-x
  • 11,109
  • 6
  • 28
  • 53

3 Answers3

4

For example, assuming entries are always like email space number:

usort($ary, function($a, $b) {
    $a = intval(explode(' ', $a)[1]);
    $b = intval(explode(' ', $b)[1]);
    return $a - $b;
});

or in more complicated but efficient way using Schwartzian transform:

$ary = array_map(function($x) {
    return [intval(explode(' ', $x)[1]), $x];
}, $ary);

sort($ary);

$ary = array_map(function($x) {
    return $x[1];
}, $ary);
georg
  • 195,833
  • 46
  • 263
  • 351
1
<?php
$data = Array(0 => 'ripe@hobby.nl 20140827',
    1 => 'bas@hobby.nl 20130827',
    2 => 'bas@dikkenberg.net 20140825',
    3 => 'bas@hobby.nl 20120825',
    4 => 'ripe@hobby.nl 20140826'
);

$count_data = count($data);

for($i=0;$i<$count_data;$i++)
{
    $new_data[trim(strstr($data[$i], ' '))]=$data[$i];
}
echo "<pre>"; print_r($new_data);
?>

this will return you

Array
(
    [20140827] => ripe@hobby.nl 20140827
    [20130827] => bas@hobby.nl 20130827
    [20140825] => bas@dikkenberg.net 20140825
    [20120825] => bas@hobby.nl 20120825
    [20140826] => ripe@hobby.nl 20140826
)

Now you can sort according to need by Key

Veerendra
  • 2,450
  • 2
  • 20
  • 39
  • You didn't actually sort the array, you merely mention it in a footnote to your code-only answer. Please improve this answer with an actual sort call and some explanation as to how your answer works and why it is a good idea. – mickmackusa Sep 28 '18 at 15:02
0

You could loop through the array, explode the string on a space, ' ', then set part one $explodedString[1] as the key in a new array, then use ksort on the new array.

Untested code.

$oldArr;
$newArr = array();

foreach($oldArr as $oldStr){
    $tmpStr = explode(' ', $oldStr);
    $newArr[$tmpStr[1]] = $tmp[0]; //You could use $oldStr if you still needed the numbers.
}

ksort($newArr);
TMH
  • 5,716
  • 7
  • 44
  • 83