Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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
}
share|improve this question

2 Answers 2

up vote 1 down vote accepted

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);
share|improve this answer

Here is a method without a custom sort function.

This can be refactored if the number of columns is unknown.

<?php

$raw_records = 'Value_1|2|Value_3|Value_4|Value_5
Value_1|5|Value_3|Value_4|Value_5
Value_1|3|Value_3|Value_4|Value_5';

$records = array();

$lines = explode("\n", $raw_records);

foreach ($lines as $line_num => $dataset) {

    $dataset = explode('|', $dataset);

    $records[$dataset[1]][] = $dataset[0];
    $records[$dataset[1]][] = $dataset[2];
    $records[$dataset[1]][] = $dataset[3];
    $records[$dataset[1]][] = $dataset[4];
}

ksort($records, SORT_NUMERIC);

echo '<pre>'; var_dump($records); echo '</pre>';
?>
share|improve this answer
    
You are overcomplicating your answer, a custom sort function takes advantage of the "iteration" the sort methods do, so you only have to compare the specific condition. –  Frederic Yesid Peña Sánchez Feb 6 at 19:46

Your Answer

 
discard

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.