Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
551 views
in Technique[技术] by (71.8m points)

php - is it possible if callback in array_filter receive parameter?

I got this multiple array named $files[], which consists of keys and values as below :

[0] => Array
(
    [name] => index1.php
    [path] => http://localhost/php/gettingstarted/
    [number] => 1
)

[1] => Array
(
    [name] => index10.php
    [path] => http://localhost/php/gettingstarted/
    [number] => 2
)

[2] => Array
(
    [name] => index11.php
    [path] => http://localhost/php/gettingstarted/
    [number] => 3
)

I use this code to create a new array consist of 'name' keys only. But it failed

array_filter($files, "is_inarr_key('name')");

function is_inarr_key($array, $key)
{
    //TODO : remove every array except those who got the same $key
}

and I get this error:

array_filter() [function.array-filter]: The second argument, 'is_inarr_key('name')', should be a valid callback in C:xampphtdocsphpgettingstartedindex.php on line 15

So my questions are:

  1. Is it possible to make the call-back function on array_filter receive parameter?
  2. What is the general rule of thumb on how to use callback in any PHP built-in function?
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can create a closure on PHP ≥5.3.

array_filter($files, function($array) use ($key) {
  return is_inarr_key($array, $key); 
} );

If you are stuck with PHP <5.3, …

You can make $key a global variable.

function is_inarr_with_global_key($array) {
   global $key;
   ....
}

You can create a class

class KeyFilter {
  function KeyFilter($key) { $this->key = $key; }
  function is_inarr_key($array) { ... }
}
...
array_filter($files, array(new KeyFilter('name'), 'is_inarr_key'));

You can create 3 different functions

array_filter($files, 'is_inarr_name');
array_filter($files, 'is_inarr_path');
array_filter($files, 'is_inarr_number');

You can write your own array_filter

function my_array_filter($files, $key) {
  ...
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...