Joe Merra
Joe Merra

Reputation: 29

get key in array php and then sort array with the keys?

if i have a array

Array
(
[3] => Array
    (
        [0] => title = title dffgfghfdg
        [1] => 2-title2
        [2] => content = content 2
    )

[1] => Array
    (
        [0] => title = title erer
        [1] => 1-title1
        [2] => content = content 1
    )

[0] => Array
    (
        [0] => title = title sdfdf
        [1] => 4-title4
        [2] => content = content 4
    )

[2] => Array
    (
        [0] => title = titledfdf df
        [1] => 3-title3
        [2] => content = content 3
    )
) 

and i will make every [1] to be key. becouse i will sort the array within [1]..?

probably will be

Array
(
[2-title2] => Array
    (
        [0] => title = title dffgfghfdg
        [1] => 2-title2
        [2] => content = content 2
    )

[1-title1] => Array
    (
        [0] => title = title erer
        [1] => 1-title1
        [2] => content = content 1
    )

[4-title4] => Array
    (
        [0] => title = title sdfdf
        [1] => 4-title4
        [2] => content = content 4
    )

[3-title3] => Array
    (
        [0] => title = titledfdf df
        [1] => 3-title3
        [2] => content = content 3
    )
)

then i will sort with the keys? thanks

Upvotes: 1

Views: 134

Answers (2)

lqez
lqez

Reputation: 3008

Use usort for it. http://php.net/manual/en/function.usort.php

function user_cmp( $a, $b )
{
    if( $a[1] == $b[1] ) return 0;
    return ($a[1] < $b[1]) ? -1 : 1;
}

$arr = array( ... );
usort( $arr, 'user_cmp' );

Upvotes: 3

Alexis Wilke
Alexis Wilke

Reputation: 20720

Use a foreach() to transform the array, then use ksort().

foreach($a as $k => $v) {
   $b[$v[1]] = $v;
}
ksort($b);

Something like that.

Upvotes: 3

Related Questions