我得到了这个名为
$files[]
的多重数组,它由以下键和值组成:
[
[
'name' => 'index1.php',
'path' => 'http://localhost/php/gettingstarted/',
'number' => 1,
],
[
'name' => 'index10.php',
'path' => 'http://localhost/php/gettingstarted/',
'number' => 2,
],
[
'name' => 'index11.php',
'path' => 'http://localhost/php/gettingstarted/',
'number' => 3,
],
]
我使用此代码创建一个仅由“名称”键组成的新数组。但失败了
array_filter($files, "is_inarr_key('name')");
function is_inarr_key($array, $key)
{
//TODO : remove every array except those who got the same $key
}
我收到此错误:
array_filter() [function.array-filter]:第二个参数 'is_inarr_key('name')' 应该是第 15 行 C:\xampp\htdocs\php\gettingstarted\index.php 中的有效回调
所以我的问题是:
array_filter
上的回调函数接收参数?您可以在 PHP ≥5.3 上创建闭包。
array_filter($files, function($array) use ($key) {
return is_inarr_key($array, $key);
} );
如果你被 PHP 困住了 <5.3, …
您可以将
$key
设为全局变量。
function is_inarr_with_global_key($array) {
global $key;
....
}
您可以创建一个班级
class KeyFilter {
function KeyFilter($key) { $this->key = $key; }
function is_inarr_key($array) { ... }
}
...
array_filter($files, array(new KeyFilter('name'), 'is_inarr_key'));
您可以创建 3 种不同的功能
array_filter($files, 'is_inarr_name');
array_filter($files, 'is_inarr_path');
array_filter($files, 'is_inarr_number');
你可以自己写
array_filter
function my_array_filter($files, $key) {
...
}
array_walk
函数:
$arr = array(
array("name" => "Jack", "id" => 1),
array("name" => "Rose", "id" => 2),
);
$result = array(); // initialize result array.
array_walk($arr, "filter"); // iterate over the array calling filter fun for each value.
// $result will now have elements "Jack" and "Rose"
function filter($a) {
global $result; // to access the global result array.
$result[] = $a['name']; // for each array passed, save the value for the key 'name' in the result array.
}
我不知道您是否可以为回调函数提供参数,但作为建议,您可以为
array_filter
定义一个回调函数
array_filter($files, "is_inarr_key");
要获取数组的
name
,只需循环 $file[]
并检索 name.
然后,有了 name
,您就可以继续您的逻辑了。
HTH.
您可以在 5.2.x 中使用 create_function()
$y = 5;
$func = 'return $x > ' . $y . ';';
$f = create_function('$x', $func);
$numbers = range(0, 10);
$result = array_filter($numbers, $f);
print_r($result);
输出
数组 ( [6] => 6 [7] => 7 [8] => 8 [9] => 9 [10] => 10 )
感谢 KennyTM 提供 keyfilter 类很棒的提示。 对于那些关心但不知道如何做的人来说,这是一个有效的详细示例。 我使用正则表达式模式略有改进。
$files[]= {上面的代码};
class KeyFilter {
function KeyFilter($attr,$pattern)
{
$this->attr=$attr;
$this->pattern=$pattern;
}
function is_inarr_key($t)
{
return preg_match($this->pattern,$t[$this->attr]);;
}
}
$t=array_filter($items, array(new KeyFilter("path","~\d{2}\.php~i"), 'is_inarr_key'));
print_r($t);
print_r($o->key);
输出:
[1] => Array
(
[name] => index**10**.php
[path] => http://localhost/php/gettingstarted/
[number] => 2
)
[2] => Array
(
[name] => index**11**.php
[path] => http://localhost/php/gettingstarted/
[number] => 3
)