sort associate array --php

Hello,
  I would like to sort the array below by Status or count. How I can do this in PHP?

Thanks for your help

Array
(
    [A1] => Array
        (
            [0] => Array
                (
                    [FileDate] => 2013-08-29
                    [Status] => Processed
                    [Count] => 8
                    [LastTransferTimeStamp] => 2013-08-29 00:18:35
                    [TotalSize] => 4564437
                )

        )

    [A2] => Array
        (
            [0] => Array
                (
                    [FileDate] => 2013-08-29
                    [Status] => Processed
                    [Count] => 14
                    [LastTransferTimeStamp] => 2013-08-29 02:10:35
                    [TotalSize] => 381075
                )

        )

    [A3] => Array
        (
            [0] => Array
                (
                    [FileDate] => 2013-08-29
                    [Status] => Pending
                    [Count] => 9
                    [LastTransferTimeStamp] => 2013-08-29 01:26:55
                    [TotalSize] => 929582
                )

        )
}

Open in new window

SiemensSENAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

gr8gonzoConsultantCommented:
I would first flatten the array and then use a multidimensional sort. I've provided a wrapper function for it, since it's a bit of a complex function:

<?php
$unsortedArray = <the original, unsorted array>;
$flattenedArray = array();

// Flatten
foreach($unsortedArray as $topKey => $keyContents)
{
  $flattenedArray[$topKey] = $keyContents[0];
}

$sortedArray = mdarray_sort($flattenedArray, "Status", SORT_ASC);

// Wrapper for array_multisort
// Usage: $arr = mdarray_sort($arr,"Column",SORT_ASC);
function mdarray_sort($srcArray,$sortColumn,$sortDirection = 4)
{
     $arrSortData = array();
     foreach($srcArray as $srcIDX => $srcRow)
          $arrSortData[$srcIDX] = $srcRow[$sortColumn];
     array_multisort($arrSortData,$sortDirection,$srcArray);
     return $srcArray;
}
?>
0
Julian HansenCommented:
You can use the usort() function (http://www.php.net/manual/en/function.usort.php)
Sample
<pre>
<?php
$x = array (
    'A1' => array(
        array (
            'FileDate' => '2013-08-29',
            'Status' => 'Processed',
            'Count' => 8,
            'LastTransferTimeStamp' => '2013-08-29 00:18:35',
            'TotalSize' => '4564437'
        )

    ),
    'A2' => array(
        array(
            'FileDate' => '2013-08-29',
            'Status' => 'Processed',
            'Count' => 14,
            'LastTransferTimeStamp' => '2013-08-29 02:10:35',
            'TotalSize' => '381075'
        )

    ),
    'A3' => array(
        array(
            'FileDate' => '2013-08-29',
            'Status' => 'Pending',
            'Count' => 9,
            'LastTransferTimeStamp' => '2013-08-29 01:26:55',
            'TotalSize' => '929582'
        )
    )
);
// Call user defined sort with compare function
usort($x, 'compare');

// Return < 0, == 0, > 0 for comparison
function compare($a, $b)
{
    return $a[0]['Count'] - $b[0]['Count'];
}
print_r($x);
?>
</pre>

Open in new window

0
Ray PaseurCommented:
As a general rule, I would go with usort() but as I look at the data set, I'm made to wonder ... will there every be any more than one element in the array below the A1, A2, A3 elements?  If the answer is, "no" it makes sense to me to flatten the array.  It looks to me like this data may be unnecessarily complex.  Maybe if you tell us where it came from, we would be able to suggest a better solution that used a simpler data structure.
0
CompTIA Security+

Learn the essential functions of CompTIA Security+, which establishes the core knowledge required of any cybersecurity role and leads professionals into intermediate-level cybersecurity jobs.

SiemensSENAuthor Commented:
Thanks..

Yes, there could be more element in the array. I am using  JQgrid to display the the data. First , I read the data for the DB group by category[A1,A2,A3]. The query also have a sum function for the count and size . Second, I convert to JSON and feed the data to JQgrid.

The above  works and I can see the data but now I would like to sort by the selected column [size,count etc..]


I will post the PHP code and JQgrid code..

Thanks for your time
0
Ray PaseurCommented:
If you can forgive the use of a global variable...  It would be so much nicer if I could pass a third parameter to the usort() function call, but I can't seem to get my head around it this morning.

<?php // RAY_temp_siemensen.php
error_reporting(E_ALL);

// SEE http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/Q_28231186.html

// A FUNCTION TO COMPARE BY NAMES
function compare_deep($a, $b)
{
    global $k;
    if     ($a[0][$k] == $b[0][$k]) return 0;
    return ($a[0][$k]  < $b[0][$k]) ? -1 : 1;
}

// TEST DATA
$arr = array (
    'A1' => array(
        array (
            'FileDate' => '2013-08-29',
            'Status' => 'Processed',
            'Count' => 8,
            'LastTransferTimeStamp' => '2013-08-29 00:18:35',
            'TotalSize' => '4564437'
        )

    ),
    'A2' => array(
        array(
            'FileDate' => '2013-08-29',
            'Status' => 'Processed',
            'Count' => 14,
            'LastTransferTimeStamp' => '2013-08-29 02:10:35',
            'TotalSize' => '381075'
        )

    ),
    'A3' => array(
        array(
            'FileDate' => '2013-08-29',
            'Status' => 'Pending',
            'Count' => 9,
            'LastTransferTimeStamp' => '2013-08-29 01:26:55',
            'TotalSize' => '929582'
        )
    )
)
;


// DETERMINE WHAT INDEXES WE CAN USE FOR THE SORT
$ndxs = array_keys($arr['A1'][0]);

// IF THE REQUEST TELLS US A VALID INDEX
$k = !empty($_GET['k']) ? $_GET['k'] : NULL;
if (!in_array($k, $ndxs)) $k = NULL;
if ($k)
{
    // SORT ACCORDING TO CHOICE
    usort($arr, 'compare_deep');

    // SHOW THE WORK PRODUCT
    echo '<pre>';
    print_r($arr);
    echo '</pre>';
}

// PUT UP THE FORM
$get = '<form>' . PHP_EOL;
$get .= 'SORT BY: <br/>' . PHP_EOL;
foreach ($ndxs as $ndx)
{
    $get .= '<input name="k" type="radio" value="' . $ndx . '">' . $ndx . '<br/>' . PHP_EOL;
}
$get .= '<input type="submit" />' . PHP_EOL;
$get .= '</form>';
die($get);

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
SiemensSENAuthor Commented:
.
0
SiemensSENAuthor Commented:
Thank you
0
Ray PaseurCommented:
For future reference, please see the last example in this article... It's got a useful approach to the problem !
http://www.experts-exchange.com/articles/18319/Using-PHP-usort-to-Simplify-Complex-Data-Search.html
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
PHP

From novice to tech pro — start learning today.