简体   繁体   中英

help me with php array sorting

I have this array

$arr = array('test1', 'test', 'test3', 'var1', 'var5', 'var');

and I want to trim/sort the array to be like this

$arr = array('test', 'var');

This question is a little vague; it sounds to me like you're asking how to filter out the elements that do not contain a digit, and the provided $arr is just an example. In which case you can do the following:

$arr = array('test1', 'test', 'test3', 'var1', 'var5', 'var');

function filter($element)
{
  if (ctype_alpha($element)) return $element;
}

$output = array_filter($arr, 'filter');

This will also work if your array changes. If you need to sort the results alphabetically, then:

natcasesort($output);

I could be wrong though; in which case this is slightly overkill.

A couple of calls to array_splice() will do it, however they cannot be nested because it expects an array reference and will not accept the output of a function call as an input parameter.

$arr = array('test1', 'test', 'test3', 'var1', 'var5', 'var');
array_splice($arr, 0, 1);
array_splice($arr, 1, 3);

print_r($arr);
Array
(
    [0] => test
    [1] => var
)
 $arr = array('test1', 'test', 'test3', 'var1', 'var5', 'var');
 $arr = array($arr[1], $arr[5]);

There's a lot of possibilities for variability if the item positions ever move around, but based on what you've posted, I think this is quickest.

$arr = array_unique(array_map('rtrim',$arr,array_fill(1,count($arr),'0123456789')));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM