这么获取数组值?
程序员文章站
2022-06-06 15:29:27
...
array(100) {
[0] => string(3) "1_1"
[1] => string(3) "2_1"
[2] => string(3) "2_2"
[3] => string(3) "3_1"
[4] => string(3) "3_2"
[5] => string(3) "3_3"
.....
}
输入"3_"就得
array(3) {
["0"] => string(1) "1"
["1"] => string(1) "2"
["2"] => string(1) "3"
请问这么取?
哦 只要后半部分
$data =array("1_1","2_1","2_2","3_1","3_2","3_3");
$need="3_";
$ret =array();
foreach($data as $item){
if(strpos($item,$need) === 0){
$ret[] = substr($item,strlen($need));
}
}
var_dump($ret);
[0] => string(3) "1_1"
[1] => string(3) "2_1"
[2] => string(3) "2_2"
[3] => string(3) "3_1"
[4] => string(3) "3_2"
[5] => string(3) "3_3"
.....
}
输入"3_"就得
array(3) {
["0"] => string(1) "1"
["1"] => string(1) "2"
["2"] => string(1) "3"
请问这么取?
回复讨论(解决方案)
$data =array("1_1","2_1","2_2","3_1","3_2","3_3");$need="3_";$ret = array_filter($data,function($item) use($need){ return strpos($item,$need) === 0;});var_dump($ret);
$d = array( "1_1", "2_1", "2_2", "3_1", "3_2", "3_3",);$in = '3_';$out = array_values( array_map(function($s) use (&$in) { return substr($s, strlen($in)); }, preg_grep("/$in/", $d)));print_r($out);
Array( [0] => 1 [1] => 2 [2] => 3)
$data =array("1_1","2_1","2_2","3_1","3_2","3_3");$need="3_";$ret = array_filter($data,function($item) use($need){ return strpos($item,$need) === 0;});var_dump($ret);
哦 只要后半部分
$data =array("1_1","2_1","2_2","3_1","3_2","3_3");
$need="3_";
$ret =array();
foreach($data as $item){
if(strpos($item,$need) === 0){
$ret[] = substr($item,strlen($need));
}
}
var_dump($ret);
下一篇: MySQL之字符集与校对集