Saturday, May 7, 2016

Sorting Multi-Dimensional Arrays in PHP

I was working on a project. I had to do lot of interaction between mysql server and my android app. In that case I got a situation where I get the raw data from database which I need to sort and show on the fly. This data is in multi dimensional array.

I use to get the items data from mysql based on the user id.


    $result = mysql_query("SELECT * FROM savedlist where uid='$uid' ") or die(mysql_error());
   if (mysql_num_rows($result) > 0) {

         $response['products'] = array();
         while ($row = mysql_fetch_array($result)) {
         // temp user array
        $itemtypes = array();
        $itemtypes['id']=$row['pid'];
     
        $result1 = mysql_query("SELECT * FROM items where id='$row[pid]'") or die(mysql_error());
     
     
        while ($row1 = mysql_fetch_array($result1)) {
         
         
        $itemtypes['name'] = $row1['name'];
        $itemtypes['price']=$row1['price'];
        $itemtypes['bay']=$row1['bay'];
         
        }
         
            print_r($itemtypes, true);
   
         // push single product into final response array
        array_push($response['products'], $itemtypes);
     
        $bays = array();
        foreach ($response['products'] as $bay)
        {  
            $bays[] = $bay['bay'];
     
        }
        array_multisort($bays,SORT_ASC, $response['products'] );
     
     
     
    }

Here
$response['products']  is  a multi dimensional array which I want to sort it based on the BAY. So first I create another array $bays[] based on the bay type. And then sort it using array_multisort()

I used the below function to sort  $response['products'] array based on $bays as:

 array_multisort($response['products'], SORT_ASC, $bays);

That's it. Happy Coding

No comments: