Sort a php array returning new array

对着背影说爱祢 提交于 2019-12-01 00:56:41

问题


I am looking for a reliable standard method to sort an array, returning the sorted ( associative ) array, as return value.

All the PHP.net functions I have read about return BOOLEAN value, or 0-1. The method I need would be something like:

$some_mixed_array = array( 998, 6, 430 );
function custom_sort( $array )
{ 
  // Sort it
  // return sorted array
}

custom_sort( $some_mixed_array );

// returning: array( 6, 430, 998 )

No need to handle strings, just INT-s.


回答1:


Would you be able to do this?

$some_mixed_array = array( 998, 6, 430 );
function custom_sort( $array )
{
  // Sort it
  asort($array);

  // return sorted array
  return $array;
}

custom_sort( $some_mixed_array );

// returning: array( 6, 430, 998 )

This would also solve your issue:

$some_mixed_array = array( 998, 6, 430 );
echo '<pre>'.print_r($some_mixed_array, true).'</pre>';

asort($some_mixed_array); // <- BAM!

// returning: array( 6, 430, 998 )
echo '<pre>'.print_r($some_mixed_array, true).'</pre>';



回答2:


Here's a one-liner:

call_user_func(function(array $a){asort($a);return $a;}, $some_mixed_array);




回答3:


As others have said, your best bet is to create a custom function. However, in order to maintain flexibility with the future of PHP, I would use a variadic function. Essentially, you set your function to accepts whatever parameters are passed to it, and pass them through to the actual sort() function. Done this way, you can use whatever optional parameters exist for the standard function you're putting the wrapper around -- even if those parameters change in the future.

function mysort( ...$params ) {
    sort( ...$params );
    return $params[0];
}


来源:https://stackoverflow.com/questions/18720682/sort-a-php-array-returning-new-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!