2

I need help for my absolute-noob question about array sorting. I'm using a function I found here: Group array results in Alphabetic order PHP to sort array values alphabetically.

$records = ['Aaaaa', 'Aaaa2', 'bbb', 'bbb2', 'Dddd'];
$lastChar = '';
sort($records, SORT_STRING | SORT_FLAG_CASE);
foreach($records as $val) {
  $char = $val[0]; //first char

  if ($char !== $lastChar) {
    if ($lastChar !== '')
      echo '<br>';

    echo strtoupper($char).'<br>'; //print A / B / C etc
    $lastChar = $char;
  }

 echo $val.'<br>';
}
?>

[ EDIT ] What i would like to do is to export each alphabetic group of array values into files, without even echoing, that would go:

foreach(){
 $group = ??; //group values alphabetically into a variable
 export($group); //input the variable into my exporting function.
}

So that the end result is I would have separate files (ie: a.txt, b.txt -- z.txt). I think this can be done with the function above, I just don't know where to put the exporting function.

Hope I'm not too confusing.

Community
  • 1
  • 1
Juneedo
  • 43
  • 3

1 Answers1

1

The simplest solution is to just call the function where you echo out already.

For example:

echo '<br>'; // you can remove this line - its a marker for where to put it.
functionToCall();

Better yet, if you wrote this as a function to be reusable, you could accept a callback as an argument. For example:

function mySortFunction($records, callable $callback) {
  // ... do some sorting
  $callback(); // calls the function a.k.a. callback.
  // ... do some more sorting
}

And call it like:

mySortFunction(['somedata'], 'myFunctionName');
// OR
mySortFunction(['somedata'], function() {
    // write your callback function here if its short.
});

Alternatively if you wanted to turn this function into a generator instead, you could yield results. Broadly speaking, a yield would replace an echo

For example:

function mySortFunction($records) {
  // do some sorting
  yield $someValue;
  // continue to do more sorting.
}

Then you could use it like:

$last = '';
$generator = mySortFunction($records);
foreach($generator as $result) {
  if(substr($result, 0, 1) != $last && $last != '') {
    echo "<br>"; // put an extra line between each letter
  }
  echo $result
}
developerjack
  • 1,173
  • 6
  • 15
  • tried this. sorry, but it doesn't event echoed the
    . i just need to call my function after each grouping. or let me edit my question.
    – Juneedo Dec 27 '15 at 16:02