Jump to content

Help splitting an array into arrays


Rifts

Recommended Posts

Hey guys,

 

I have an array of names sorted alphabetically. I'm trying to loop through them and create new arrays keyed by the letters of the alphabet containing the names which start with that letter.

 

 

so in the end i'm trying to create something like this:

 

$newarray = array( 'a' => array('anna','alan','andrew'),

                               'b' => array('bert','ben','bob'),
                               'c' => array('cait','carry'),

                                 etc,etc );

 

thanks

 

 

 

 

Link to comment
https://forums.phpfreaks.com/topic/291511-help-splitting-an-array-into-arrays/
Share on other sites

do you mean

$nums = array (1234,28975,9258,44,950,40582,21,456);
    sort($nums);
    foreach ($nums as $n) {
        $x = "$n";    // cast the number as a string
        $newArray[$x[0]][] = $n;
    }

Gives

Array
(
    [2] => Array
        (
            [0] => 21
            [1] => 28975
        )

    [4] => Array
        (
            [0] => 44
            [1] => 456
            [2] => 40582
        )

    [9] => Array
        (
            [0] => 950
            [1] => 9258
        )

    [1] => Array
        (
            [0] => 1234
        )

)

No sorry for not explaining better.

 

I meant 

 

$names = array ('anna','bert','ben','cait','alan','andrew','bob','carry', '23 kenny','10','43 lala');

 

I was going to try something like this

foreach ($names as $n) {

       if( is_numeric($n)) {
           $newArray[$n[0]]['#'] = $n;
       } else {
        $newArray[$n[0]][] = $n;

       }
    }

OK, plan B

    $names = array ('anna','bert','ben','cait','alan','andrew','bob','carry', '23 kenny','10','43 lala');
    sort($names); 
    foreach ($names as $n) {
        $x = "$n";    // cast the name as a string
        if (is_numeric($x[0]))
            $newArray['#'][] = $n;
        else
            $newArray[$x[0]][] = $n;
    }

Gives

Array
(
    [#] => Array
        (
            [0] => 10
            [1] => 23 kenny
            [2] => 43 lala
        )

    [a] => Array
        (
            [0] => alan
            [1] => andrew
            [2] => anna
        )

    [b] => Array
        (
            [0] => ben
            [1] => bert
            [2] => bob
        )

    [c] => Array
        (
            [0] => cait
            [1] => carry
        )

)

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.