PHP: Sort the array by the exploded value

advertisements

How can I sort an array by a value from an exploded string?

To make it a bit more clear, I have data stored in a textfile in the following format:

Value_1|Value_2|Value_3|Value_4|Value_5
Value_1|Value_2|Value_3|Value_4|Value_5
Value_1|Value_2|Value_3|Value_4|Value_5
...

I read the data using

$data_file = 'foo.txt';
$lines = file($data_file, FILE_IGNORE_NEW_LINES);

then explode each line and output the content (HTML stripped to keep it clean)

foreach ($lines as $line_num => $dataset) {
  $dataset = explode('|', $dataset);
  //echo exploded values + some HTML
}

However, before I output the data, I want to sort the array by Value_2 (which is always a number) from e.g. high to low. Do I have to set the keys of the array to Value_2 and then sort it? How can I do that? What would be the best solution here?

Thanks for your help!


This is the final, slightly modified snippet for everyone who's interested:

$data_file = 'foo.txt';
$lines = file($data_file, FILE_IGNORE_NEW_LINES);

function sort_data_array($a, $b){
    $ex_a = explode('|', $a);
    $ex_b = explode('|', $b);
    if ($ex_a[1] == $ex_b[1]) {return 0;}
    return ($ex_a[1] > $ex_b[1]) ? -1 : 1;
}

uasort($lines, 'sort_data_array');
$lines = array_values($lines);

foreach ($lines as $line_num => $dataset) {
    //output
}


Use a custom sort function:

EG:

uasort($lines, function($a , $b){
    $ex_a = explode('|', $a);
    $ex_b = explode('|', $b);

    return (strcmp($ex_a[1], $ex_b[1]) < 0 ? 1: -1); // change the < to > if they are in reverse...

}

print_r($lines);