1

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
}

2 Answers 2

1

Use a custom sort function:

EG:

uasort ($lines, function($a , $b)) {

    $ex_a = explode('|', $a);
    $ex_b = explode('|', $b);

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

}

print_r($lines);
Sign up to request clarification or add additional context in comments.

Comments

0

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>';
?>

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.