Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have an array of IP networks

<?php
$array = array(
    '217.192' => array(
        array(
            'ip' => '217.192.133.52',
            'id' => '1',
        ),
        array(
            'ip' => '217.192.98.111',
            'id' => '2',
        ),
    ),
    '21.170' => array(
        array(
            'ip' => '21.170.171.23',
            'id' => '3',
        ),
        array(
            'ip' => '21.170.212.22',
            'id' => '4',
        ),
    ),
    '148.11' => array(
        array(
            'ip' => '148.11.11.12',
            'id' => '5',
        ),
        array(
            'ip' => '148.11.122.33',
            'id' => '6',
        ),
        array(
            'ip' => '148.11.22.89',
            'id' => '7',
        ),
    ),
    '72.1' => array(
        array(
            'ip' => '72.1.98.9',
            'id' => '8',
        ),
    ),
);

I need to output this array ordering by count AND sort by subnetwork (key of array).

arsort($array) dont works like i want.

I need 148.11, 21.170, 217.192, 72.1 AND inside these so sort ips...

Sorry for bad english!

share|improve this question

2 Answers 2

up vote 1 down vote accepted

Try this:

function sortHelper(array $a, array $b) {
    $aCnt = count($a);
    $bCnt = count($b);
    if ($aCnt == $bCnt) {
        return 0;
    } else if ($aCnt > $bCnt) {
        return -1;
    } else {
        return 1;
    }
}

uasort($array, 'sortHelper');

// UPDATE: sort inside by IP

function ipSortHelper(array $a, $b) {
    $aIp = ip2long($a['ip']);
    $bIp = ip2long($b['ip']);
    if ($aIp == $bIp) {
        return 0;
    } else if ($aIp < $bIp) {
        return -1;
    } else {
        return 1;
    }
}

foreach ($array as $prefix => $group) {
    uasort($group, 'ipSortHelper');
    $array[$prefix] = $group;
}
share|improve this answer
    
It works! Thank you so much. How I can sort ip inside array? –  Isis Apr 9 '12 at 13:41
    
See updated answer –  Tamas Imrei Apr 9 '12 at 13:53

You will have to use a "custom sort function": http://www.php.net/usort and write the logic for sorting yourself.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.