开发者

Get a sub array with a pattern in php

Consider this array in PHP:

$list = array('apple','orange','alpha','bib','so开发者_StackOverflow中文版n','green','odd','soap');

How can i get a sub array of elements start with letter 'a' or 's' ?


http://php.net/manual/en/function.preg-grep.php

$items = preg_grep('~^[as]~', $list);


Check out array_filter here: http://www.php.net/manual/en/function.array-filter.php

$list = array_filter($list, function ($a) { return $a[0] == 'a' || $a[0] == 's'; });


$sublist = array();
for ($i = 0; $i < count($list); $i++) {
    if ($list[$i][0] == 'a' or $list[$i][0] == 's') {
        $sublist[] = $list[$i];
    }
}


for ($i =0; $i < count($list); $i++) {
    if (substr($list[i], 1) == "a" || substr($list[i], 1) == "s") {
        //put it in an other array
    }
}


<?php

$list = array('apple','orange','alpha','bib','son','green','odd','soap');

$tmp_arr = array(); foreach ($list as $t) { if (substr($t, 0, 1) == 'a' || substr($t, 0, 1) == 's') { $tmp_arr[] = $t; } }

print_r($tmp_arr);

?>

//output: Array ( [0] => apple [1] => alpha [2] => son [3] => soap )


This is one way of doing it:

    $list = array('apple','orange','alpha','bib','son','green','odd','soap');


$a = array();
$s = array();
for ($i = 0; $i < count($list); $i++)
{
    if (substr($list[$i], 0, 1) == "s")
    {
        $s[$i] = $list[$i];
    }
    else if (substr($list[$i], 0, 1) == "a")
    {
        $a[$i] = $list[$i];
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜