Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing userdata to array_walk and reference to self

I have to filter multidimensional array by searched keyword.

I'm using array_walk but i couldnt send searched keyword inside to array_walk in class

multidimensional array

Array
(
    [0] => SimpleXMLElement Object
        (
            [plugin_name] => Custom Extension
        )

    [1] => SimpleXMLElement Object
        (
            [plugin_name] => Hello World
        )

    [2] => SimpleXMLElement Object
        (
            [plugin_name] => Test Plugin
        )

)

I tried following functions:

First one

array_walk($lists, function(&$value, $index){
    if (stripos($value->plugin_name, $this->search) === false)
        unset($lists[$index]);
});

This gives me Fatal error: Using $this when not in object context in

Second one

$search = $this->search;
array_walk($lists, function(&$value, $index){
    if (stripos($value->plugin_name, $search) === false)
        unset($lists[$index]);
});

I couldn't get $search var from array_walk function

Third one

$search = $this->search;
array_walk($lists, function (&$value, $index) use ($search) {
if (stripos($value->plugin_name, $search) !== false)
    return $value;
});

$search passed successfully with use keyword but $lists array didnt change so not referenced. Why?

What should I do or use another function instead of array_walk?

Solution

$params = array('search' => $this->search, 'data' => $lists);

array_walk($lists, function (&$value, $index) use (&$params) {
if (stripos($value->plugin_name, $params['search']) === false)
  unset($params['data'][$index]);
});

$lists = $params['data'];

I sent params with use keyword as array and reference to self.

like image 758
Bora Avatar asked Sep 17 '13 13:09

Bora


1 Answers

You need to use the use keyword.

array_walk($lists, function (&$value, $index) use ($search) {

PHP is not like JavaScript, so the anonymous function is still in a different scope, but that is what use is for. I would link to the documentation on use, but there does not seem to be any.

like image 165
Explosion Pills Avatar answered Nov 10 '22 08:11

Explosion Pills