views:

217

answers:

3

i got this multiple array name $files[], who consist 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
        )

and i use this code to create 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 got this error

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

so the queastion : 1. is it possible to make call-back function on array_filter has ability to receive parameter ?

  1. What is general rule of thumb on how to use callback in anyPHP built-in function ?
+1  A: 

I am unaware if you can supply the callback function with parameters, but as a suggestion, you could define a callback function for array_filter

array_filter($files, "is_inarr_key");

And to get the name of the array, just loop over the $file[] and retrieve the name. Then, having the name you can go on with your logic.

HTH.

Anthony Forloney
+5  A: 

You can make $key a global variable.

function is_inarr_key($array, $key) {
   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 a closure on PHP ≥5.3.

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

You can create 3 different functions

array_filter($files, 'is_inarr_name');

You can write your own array_filter

function my_array_filter($files, $key) {
  ...
}
KennyTM
i haven't try it. but this solution's brilyan. if i convert my code work with closure or class, i will able to work with more keys AND create ONLY one fun ction : is_inarr_key()
justjoe
+1  A: 

You can make use of the array_walk function as:

$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.
}
codaddict