1

i am trying to access $managers variable in change function.

public function ManagerPerDay() {
        $query = $this->mysqli()->query('SELECT
                                            manager,
                                            count(manager) AS count
                                        FROM
                                            DATA
                                        GROUP BY
                                            manager
                                        ORDER BY
                                            count DESC');
        $data = $query->fetch_all();

        $managers = $this->GetManagers();

        function Change($n)
        {
            $name = $managers[array_search($n[0], array_column($managers, 'id'))]['name'];
            $n[0] = $name;
            return $n;
        }

        $data = array_map('Change', $data);

        array_unshift($data, ['Manager', 'Per Day']);
        return $data;
    }

i have tried global $managers; in change function but it also does not work.

2
  • You can declare a function inside a function, but calling the outside function more than once will result in a redeclaration error for the inner function. Better to use a closure here. Commented Nov 22, 2016 at 14:25
  • The reason your global declaration didn't work is because you'd need to declare $managers global within both functions. Commented Nov 22, 2016 at 14:28

2 Answers 2

2

Use array_walk which allows you to add your parameters

function Change(&$n, $key, $managers)
        {
            $name = $managers[array_search($n[0], array_column($managers, 'id'))]['name'];
            $n[0] = $name;            
        }

        array_walk($data, 'Change', $managers);
Sign up to request clarification or add additional context in comments.

2 Comments

@BARNI, if the answer was useful you may click the checkmark ✔ to accept it (this is how you reward people for their effort).
Sorry, was not online (checked ✔).
0

You could use the use keyword to pass that variable to the function. Something like this for example:

$data = array_map(function($n) use ($manager) {
    $name = $managers[array_search($n[0], array_column($managers, 'id'))]['name'];
    $n[0] = $name;
    return $n;
}, $data);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.