i have a two dimensional array e.g
( [0] => Array ( [person_id] => 55487 [score] => 1.30427 [mistakes] => 103.874811 [description] => first record ) [1] => Array ( [person_id] => 55487 [score] => 1.30427 [mistakes] => 103.874811 [description] => second record ) )
then I have a class function called
public function saveData($dbConnection, $param) { // function definition here }
now how to use the array_walk with this function ?
I tried
array_walk($myArray,[$this,'saveData'],$dbConnection,$param);
I tried
array_walk($myArray,[$this,'saveData'],[$dbConnection,$param]);
none of these work..how to do it ?
Advertisement
Answer
According to documentation of array_walk:
Especially this line:
If the optional userdata parameter is supplied, it will be passed as the third parameter to the callback.
The extra parameter $userdata
has to be at the 3rd parameter of your $callback
. There is no way to workround the parameter order in array_walk()
. But your method is clear using $dbConnection
as the 1st parameter in your saveData()
method.
There are 2 sensible ways to solve this:
Change your class method. Either to store the database connection in your class instance to remove it entirely from the parameter needs:
public function saveData($param) { $dbConnection = $this->$dbConnection; // has to set this attr. somewhere else. // function definition here } // ... // call it like this: array_walk($myArray, [$this,'saveData']);
or change the parameter order accord to the
$callback
requirementpublic function saveData($param, $key, $dbConnection) { // function definition here } // ... // call it like this: array_walk($myArray, [$this,'saveData'], $dbConnection);
Keep the method. Use an intermediate callback function instead:
// call it like this in your method: array_walk($myArray, function ($param, $key, $dbConnection) { return $this->saveData($dbConnection, $param); }, $dbConnection);