Q:

Write a PHP program to sort a multi-dimensional array set by a specific key

0

Write a PHP program to sort a multi-dimensional array set by a specific key

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

<?php
function column_Sort($unsorted, $column) { 
    $sorted = $unsorted; 
    for ($i=0; $i < sizeof($sorted)-1; $i++) { 
      for ($j=0; $j<sizeof($sorted)-1-$i; $j++) 
        if ($sorted[$j][$column] > $sorted[$j+1][$column]) { 
          $tmp = $sorted[$j]; 
          $sorted[$j] = $sorted[$j+1]; 
          $sorted[$j+1] = $tmp; 
      } 
    } 
    return $sorted; 
} 
$my_array = array(); 
$my_array[0]['name'] = 'Sana'; 
$my_array[0]['email'] = 'sana@example.com'; 
$my_array[0]['phone'] = '111-111-1234'; 
$my_array[0]['country'] = 'USA'; 

$my_array[1]['name'] = 'Robin'; 
$my_array[1]['email'] = 'robin@example.com'; 
$my_array[1]['phone'] = '222-222-1235'; 
$my_array[1]['country'] = 'UK'; 

$my_array[2]['name'] = 'Sofia'; 
$my_array[2]['email'] = 'sofia@example.com'; 
$my_array[2]['phone'] = '333-333-1236'; 
$my_array[2]['country'] = 'India'; 
print_r(column_Sort($my_array, 'name')); 
?>

Sample Output:

Array                                                       
(                                                           
    [0] => Array                                            
        (                                                   
            [name] => Robin                                 
            [email] => robin@example.com                    
            [phone] => 222-222-1235                         
            [country] => UK                                 
        )                                                   
                                                            
    [1] => Array                                            
        (                                                   
            [name] => Sana                                  
            [email] => sana@example.com                     
            [phone] => 111-111-1234                         
            [country] => USA                                
        )                                                   
                                                            
    [2] => Array                                            
        (                                                   
            [name] => Sofia                                 
            [email] => sofia@example.com                    
            [phone] => 333-333-1236                         
            [country] => India                              
        )                                                   
                                                            
)

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Similar questions


need a help?


find thousands of online teachers now