Jump to content

How to sort multidimensional arrays by array or string type


Xeoncross

Recommended Posts

 

 

I have an array that contains strings and other arrays. I need to know how to sort it so that the strings are at the top of the array and the arrays are at the bottom of the array.

 

<?php

$myarray = array(
    0 => array(
        'sub1' => array('value' => 'Sub One', 'comment' => 'This is sub1'),
        'sub2' => 'Sub Two',
    ),
    1 => 'Value 1',
    2 => array(
        'sub1' => array('value' => 'Sub One', 'comment' => 'This is sub1'),
        'sub2' => 'Sub Two',
    ),
    3 => 'Value 3'
);

///////////////into

$myarray = array(
    0 => 'Value 1',
    1 => 'Value 3',
    2 => array(
        'sub1' => array('value' => 'Sub One', 'comment' => 'This is sub1'),
        'sub2' => 'Sub Two',
    ),
    3 => array(
        'sub1' => array('value' => 'Sub One', 'comment' => 'This is sub1'),
        'sub2' => 'Sub Two',
    )
);

?>

 

My guess is that usort() should be used somehow. I just don't want to have to cycle through each array piece and LOOK at it to check if it is an array or not...

 

I actually read your post.

 

<?php
$myarray = array(
    0 => array(
        'sub1' => array('value' => 'Sub One', 'comment' => 'This is sub1'),
        'sub2' => 'Sub Two',
    ),
    1 => 'Value 1',
    2 => array(
        'sub1' => array('value' => 'Sub One', 'comment' => 'This is sub1'),
        'sub2' => 'Sub Two',
    ),
    3 => 'Value 3'
);
sort($myarray);
echo '<pre>', print_r($myarray, true), '</pre>';
?>

 

gives me

 

Array
(
   [0] => Value 1
   [1] => Value 3
   [2] => Array
       (
           [sub1] => Array
               (
                   [value] => Sub One
                   [comment] => This is sub1
               )

           [sub2] => Sub Two
       )

   [3] => Array
       (
           [sub1] => Array
               (
                   [value] => Sub One
                   [comment] => This is sub1
               )

           [sub2] => Sub Two
       )

)

 

?

 

On PHP 5.2.2 BTW.

I actually read your post.

 

So you did  8)

 

Sorry, I forgot that sort deletes the keys and then sorts by value type.

So you are correct.

 

However, I wanted to keep the keys and sort by value type - but that is impossible now that I have thought about it  ::)

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.