0

I am working on array functionality in php i face some issue with array sorting.

Array is :

$employees = array(
    123 => array(
      'id'        => 13,
      'firstname' => 'Marky',
      'lastname'  => 'Mark'
    ),
    213 => array(
      'id'        => 3,
      'firstname' => 'Bobby',
      'lastname'  => 'Bob'
    ),
    256 => array(
      'id'        => 42,
      'firstname' => 'Jimmy',
      'lastname'  => 'Jim'
    )
  );

I want this array to be sort by firstname field not affecting any of the key value

I have used

foreach( $employees as $intKey => $Data ) {
                        $arrstr[$intKey]  = $Data['firstname'];
                    }
array_multisort( $arrstr, SORT_DESC, SORT_STRING, $employees );

but this function is affecting my key value of main array and give me out put like

$employees = array(
        0=> array(
          'id'        => 3,
          'firstname' => 'Bobby',
          'lastname'  => 'Bob'
        ),
        1=> array(
          'id'        => 42,
          'firstname' => 'Jimmy',
          'lastname'  => 'Jim'
        )
        2=> array(
          'id'        => 13,
          'firstname' => 'Marky',
          'lastname'  => 'Mark'
        ),
      );

Here its affecting my key value of main array.

so please help some how to achieve the exact result without affecting the key value like :

$employees = array(
        213 => array(
          'id'        => 3,
          'firstname' => 'Bobby',
          'lastname'  => 'Bob'
        ),
        256 => array(
          'id'        => 42,
          'firstname' => 'Jimmy',
          'lastname'  => 'Jim'
        ),`enter code here`
       123 => array(
          'id'        => 13,
          'firstname' => 'Marky',
          'lastname'  => 'Mark'
        )
      );
Nilesh Solanki
  • 99
  • 3
  • 11

1 Answers1

0

1, A solution could be is to use uksort function

You just need to pass in a global variable or static property the array which should be manipulated so, the callback function can lookup key values on that.

like:

function sort_on_name( $a , $b ) {
  return strcmp(
    $GLOBALS['employees'][$a]['firstname'] ,
    $GLOBALS['employees'][$b]['firstname']
  );
}

$GLOBALS['employees']=$employees;
uksort( $employees , 'sort_on_name' );

2, another solution could be to make a helper lookup array key-value pairs on (like

$sorting = array( 'Bobby' => 213 , 'Jimmy' => 256 ... )

and simply sort that and use new helper lookup foreach as lookup on original array

lorenzodarkside
  • 146
  • 2
  • 4
  • 2
    `uksort($employees, function ($a, $b) use ($employees) { .. })` – much better than `$GLOBALS`. – deceze Nov 25 '15 at 14:01
  • I have used only some of values but the employee array which i am getting is having 10K data if i used foreach in my any of the code it will slower down the script. – Nilesh Solanki Nov 25 '15 at 14:44