圖案的子陣列考慮這個數組在PHP中:獲取與PHP
$list = array('apple','orange','alpha','bib','son','green','odd','soap');
我怎樣才能得到元素的子陣列開始字母「A」或「S」?
圖案的子陣列考慮這個數組在PHP中:獲取與PHP
$list = array('apple','orange','alpha','bib','son','green','odd','soap');
我怎樣才能得到元素的子陣列開始字母「A」或「S」?
http://php.net/manual/en/function.preg-grep.php
$items = preg_grep('~^[as]~', $list);
$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
}
}
退房array_filter
這裏:http://www.php.net/manual/en/function.array-filter.php
$list = array_filter($list, function ($a) { return $a[0] == 'a' || $a[0] == 's'; });
<?php
$名單=陣列( '蘋果', '橙', '阿爾法' , '圍脖', '兒子', '綠', '奇', '肥皂');
$ tmp_arr = array(); foreach($ list as $ t) if(substr($ t,0,1)=='a'|| substr($ t,0,1)==''') { $ tmp_arr [] = $ t; } }
print_r($ tmp_arr);
>
//輸出:?陣列([0] =>蘋果[1] =>的α[2] =>子[3] =>皁)
這是一種方式這樣做:
$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];
}
}
$ A = preg_grep( '#^ A | S#',array_map( '用strtolower',$列表));以防萬一你有混合的情況(在你的測試中使蘋果蘋果)。 +1發佈適當的PHP數組我們可以複製和使用。周到。 – Cups
啊,好吧,好吧,那麼這是更好的$ a = preg_grep('#^ a | s#i',$ list); <-use i正則表達式 – Cups