I am trying to understand how the elements from my array are passed to my value comparison function when used usort(). Printing values $xand $ythe following for each iteration:
Iteration 1:
array(2) { ["k1"]=> int(21) ["k2"]=> string(1) "e" }
array(2) { ["k1"]=> int(920) ["k2"]=> string(1) "z" }
Iteration 2:
array(2) { ["k1"]=> int(842) ["k2"]=> string(1) "t" }
array(2) { ["k1"]=> int(21) ["k2"]=> string(1) "e" }
Iteration 3:
array(2) { ["k1"]=> int(920) ["k2"]=> string(1) "z" }
array(2) { ["k1"]=> int(21) ["k2"]=> string(1) "e" }
Iteration 4:
array(2) { ["k1"]=> int(842) ["k2"]=> string(1) "t" }
array(2) { ["k1"]=> int(920) ["k2"]=> string(1) "z" }
My details:
$data = array(
array( 'k1' => 920, 'k2' => 'z' ),
array( 'k1' => 21, 'k2' => 'e' ),
array( 'k1' => 842, 'k2' => 't' )
);
My custom function:
function value_compare_func( $x, $y ) {
if ( $x['k1'] > $y['k1'] ) {
return true;
} elseif ( $x['k1'] < $y['k1'] ) {
return false;
} else {
return 0;
}
}
Array Sort:
usort( $data, 'value_compare_function' );
For the first iteration $x['k1']there is $data[1]['k1'], but $y['k1']- $data[0][k1]. Why are $datan't the elements from the array passed in value_compare_func()in order? For example, I expected $x['k1']to be $data[0]['k1']and $y['k1']for the $data[1]['k1']for the first iteration, but it was not.