Jump to content

[SOLVED] Sorting a dynamic array


nezbie

Recommended Posts

Hi, this consideres my csv manager. It reads a csv file and drops the info to a table and to inputfields so they are editable. The basic structure goes like the following (example with 2 rows and 3 columns:

[b]
|  index  |  First name  | Last name  |  ID      |[/b]

|    1    |  John          | Smith        |  2920    |
|    2    |  Harry        |  Shearer  |  1032    |

in the very first line of my csv file the column headers are defined. (in this case first name, last name, id)

I'd need to be able to sort these information by column index (name is also possible if that is what is needed)

I mentioned earlier that those information are found in inputfields. They are named like: [b]contents[rowNR][columnNR][/b], so "Shearer" is found in [b]$contents[2][2][/b]

After I edit this info it is send via form to be rewritten to it's original sourcefile using the following simple piece of code:

[code]
foreach ($_POST['contents'] as $key=>$value) {
 
  $parsedData .= implode(';', $value) . "\r\n";

}
[/code]

So what I'd need help with is sorting the array $contents[row][[b]with this key[/b]]. Also I'd need to be able to s[b]kip the row with index "0"[/b] because it is used to save the column header information. I hope you understand what I'm after here..

All help and ideas highly appreciated, thanks =)
Link to comment
Share on other sites

Not sure if it's the cleanest way, but it should get the job done:

[code]
<?php
function doSort($arr, $key){
  $tmp[] = $arr[0];
  $arr = array_slice($arr, 1);
  foreach ($arr as $a){
    $order[] = $a[0];
  }
  $order = asort($order, TRUE);
  foreach($order as $idx =>value){
    $tmp[]=$arr[$idx];
  }
  return $tmp;
}

$contents = doSort($contents, "index");
?>
[/code]
Link to comment
Share on other sites

Or, you could create the array in columns so that you can use array_multisort which youcan use to sort by columnA, then by column B, etc., or however you want it.

See the manual here: http://us3.php.net/manual/en/function.array-multisort.php

In any event it would be better design to not include the headers as a data item. Instead use the header items as the keys in the array.
Link to comment
Share on other sites

The reason it is more difficult than it needs to be is that you have included the header names as a record. The header records should be the keys of the array. If you were to put the data in columns instead of row you could sort it using just a single line with the array_Multisort() function.

If you don't want to reformat your array then you need to look at uasort() as Barand suggested. Have you looked at the manual yet?: http://us3.php.net/manual/en/function.uasort.php
Link to comment
Share on other sites

Yes I have. It's just as clear as usual ;)

I didn't quite understand the keys and headers thing.. should it be something like columnName=>[rowNumber] = value ? I've never been too good with these anyways - and if there is no at least moderately easy solution with current code logic I will just leave this feature not to be included.. It's not so important, rather "nice to have".

I don't want to rewrite my script for this. Would I have to?
Link to comment
Share on other sites

This will do it using a cutom sort function
[code]
<?php
$data = array (
    array ('index','fname','lname','id'),
    array (1, 'John', 'Smith', 2920),
    array (2, 'Harry', 'Shearer', 1032),
    array (3, 'John', 'Anderson', 5970),
    array (4, 'Harry', 'Taylor', 1256),
);

function mysort($a , $b)  {
    /**
    * custom sort function takes pairs of elements, $a and $b
    * If a should sort before b, return -1
    * If a should be after b, return 1
    * If they are equal, return 0
    */
    global $sortByCol;
    if ($a[0]=='index') return -1;
    if ($b[0]=='index') return 1;
    return strcmp($a[$sortByCol], $b[$sortByCol]);   
}

$sortByCol = 2; // set to last name col

uasort ($data, 'mysort');

// check
echo '<pre>', print_r($data, true), '</pre>';
?>
[/code]
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.