Skip to content

Instantly share code, notes, and snippets.

@webinista
Last active August 8, 2022 13:56
Show Gist options
  • Save webinista/6c4b82909a9a4c3e761f to your computer and use it in GitHub Desktop.
Save webinista/6c4b82909a9a4c3e761f to your computer and use it in GitHub Desktop.
Split an array into chunks based on the first letter of one of its column values.
<?php
global $alpha_chunks;
# Initialize array
$alpha_chunks = array();
function chunkNames(&$value, $key, $letter) {
global $alpha_chunks;
/*
If the first letter of the last name == $letter, Add the entry to a multi-dimensional array with each
$letter is the key. Change 'lastname' to match the name of that column.
*/
if ($value['lastname'][0] === $letter ) {
$alpha_chunks[$letter][$key] = $value;
}
}
# Can be any array of characters.
$atoz = range('A','Z');
foreach($atoz as $letter) {
# $array_to_walk isn't defined here, but this is should be the array you'd like to split.
array_walk($array_to_walk, 'chunkNames', $letter);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment