我有一个关于PHP的基本问题,我无法用stackoverflow中的其他答案解决它。
我有一个像:
这样的数组[0] => this one i need 1
[1] => this one i need 2
[2] => not need this one
所以,我想检查每一个,如果它包含'这个我需要',然后把它放到另一个数组
所以我们必须至少拥有这个数组:
[0] => this one i need 1
[1] => this one i need 2
我尝试这样做,但它返回空数组:
foreach($one as $value) {
if(in_array("my name",$value)) $ok[] = $value;
}
答案 0 :(得分:2)
试试这个
<?php
$one = array();
$one[0] = "this one i need 1";
$one[1] = "this one i need 2";
$one[2] = "not need this one";
$ok = array();
$find_str = "this one i need";
foreach($one as $value) {
if(strpos($value, $find_str) !==false)
{
$ok[] = $value;
}
}
print_r($ok);
?>
输出:
Array
(
[0] => this one i need 1
[1] => this one i need 2
)
<强> Demo 强>
更新2:
因为OP $value
是一个数组
$ok = array();
$find_str = "this one i need";
foreach($one as $value) {
foreach($value as $val){
if(strpos($val, $find_str) !==false)
{
$ok[] = $value;
}
}
}
print_r($ok);
答案 1 :(得分:1)
内置array_filter()功能正是为此目的而设计的
$needle = 'XYZ';
$newArray = array_filter(
$originalArray,
function ($value) use ($needle) {
return (strpos($value, $needle) !== false);
}
);
答案 2 :(得分:1)
array_filter
是基于值
$one[0] = "this one i need 1";
$one[1] = "this one i need 2";
$one[2] = "not need this one";
$wanted_string = 'this one i need';
$array_out = array_filter($one, function($var) use($wanted_string) {
return strpos($var, $wanted_string) !== false;
});
// array(2) { [0]=> string(17) "this one i need 1" [1]=> string(17) "this one i need 2" }