Michoser
Michoser

Reputation: 85

Function with arrays and single arguments

I had function simple function:

public function getGame($id_player)
{
    $query = "SELECT id_game FROM players_games WHERE id_player = ?";
    $result = $this->db->query($query, array($id_player));
    return $result->current()['id_game'];
} 

I always used a single id_player and return from it one id_game. And thats how I was using it:

$game= $element->getGame($id_player);
$gameName = $game['name'];

Now I have a array of id_players and I need to return this array of id_players and array of id_games, although I want to use this function for single id_player too (with returning id_player and id_game).

How to change this function for that and how to use it?

Upvotes: 1

Views: 29

Answers (1)

user2010925
user2010925

Reputation:

Utilize something similar to this:

public function getGame($id_player)
{
    if ( is_array($id_player) )
    {
        $query = "SELECT id_game FROM players_games WHERE id_player IN (?)";
        $result = $this->db->query($query, array(implode(',', $id_player));

        $ids = array();
        while ( $row = $result->fetch() )
        {
            $ids[] = $row['id_game'];

        }
        return $ids;
    }
    else
    {
        $query = "SELECT id_game FROM players_games WHERE id_player = ?";
        $result = $this->db->query($query, array($id_player));
        return $result->current()['id_game'];
    }
} 

This should do it for you.

Upvotes: 1

Related Questions