Page 1 of 1

Sorting multidimensional array by value before displaying

Posted: Mon Jun 13, 2016 8:50 pm
by xkevin
My current code:

Code: Select all

$masterData = array();

    $data = file("datas/payments.csv");
    foreach ($data as $deposit){
        $depositarray = explode(",", $deposit);
        $depositlist = $depositarray;
        $key = md5($depositlist[9] . number_format($depositlist[10],2)); //date + amount

        $masterData[$key]['payment'] = array(
            'name' => $depositlist[0],
            'email' => $depositlist[1],
            'depositdate' => $depositlist[9],
            'depositamount' => number_format($depositlist[10],2)                
        );

    }
usort($masterData[$key]['payment']['depositdate']);// (added)What ive tried but not working
I display it like this:

Code: Select all

 foreach($masterData as $key=>$data) {
<td><?=($data['payment']['name'])?></td>
<td><?=($data['payment']['email'])?></td>
<td><?=($data['payment']['depositdate'])?></td>
<td><?=($data['payment']['depositamount'])?></td>
}
I would like to sort it ascending by date 'depositdate'. So that it is arranged properly when I display the list. Thank you for help.

Re: Sorting multidimensional array by value before displayin

Posted: Mon Jun 13, 2016 9:47 pm
by requinix
usort() takes two arguments. Look at the documentation to see what you need to do about that.

Re: Sorting multidimensional array by value before displayin

Posted: Mon Jun 13, 2016 10:13 pm
by xkevin
requinix wrote:usort() takes two arguments. Look at the documentation to see what you need to do about that.
I added function like this

Code: Select all

function cmp($date, $date)
{
    if ($date == $date) {
        return 0;
    }
    return ($date < $date) ? -1 : 1;
}

Code: Select all

foreach (......
);
at the end of loop, I added this:

Code: Select all

$date = $masterData[$key]['payment']['depositdate'];
usort($date,"cmp");
-Any help about my code?

Re: Sorting multidimensional array by value before displayin

Posted: Tue Jun 14, 2016 12:46 am
by requinix
Ah, I missed that the first time.

usort() is for sorting arrays. You need to give it the array that you want to sort. Not a single value you got from somewhere inside it.

Your foreach loop is over $masterData. So that's what you need to sort.

Re: Sorting multidimensional array by value before displayin

Posted: Tue Jun 14, 2016 2:44 am
by xkevin
uhm..sorry, i didn't get it. Can you help me with my code? It my first time dealing with sorting