How to return array indexes in method

1

Well I could not find a better title for my case, I have the following function :

public function select_tokens() {
    $sql = "SELECT * FROM 'users'";

    $select_tokens = Database::DB()->prepare($sql);
    $select_tokens->execute();
    $fetch = $select_tokens->fetchAll(PDO::FETCH_ASSOC);

    foreach ($fetch as $token) {
        $tokens[] = [
            'user_token' => $token['user_token'],
            'user_token2' => $token['user_token2']
        ];
    }
    return $tokens;
}

Note, I am returning $tokens which in the case I could use like this:

$tk = $users->select_tokens();

And then get the index:

$tk['user_token'];

or

$tk['user_token2'];

But I do not know why this error returns me:

  

Notice: Undefined index: user_token

or

  

Notice: Undefined index: user_token2

    

asked by anonymous 31.07.2017 / 12:57

1 answer

2

You are creating an array composed of other arrays here:

$tokens[] = [
    'user_token' => $token['user_token'],
    'user_token2' => $token['user_token2']
];

So, to access the internal arrays, you have to iterate over the main array, or reference the key you want, for example:

// 0 é a chave do primeiro array criado no foreach ali em cima.
// e eles são numerados em sequência, 0, 1, 2, 3 etc
$tk[0]['user_token'];

If you want to use user_token as the primary key, you can create an array for each token type:

foreach ($fetch as $token) {
    $tokens['user_token'][] = $token['user_token'];
    $tokens['user_token2'][] => $token['user_token2'];
    ];
}

Now you can do this:

var_dump( $tokens['user_token'] );
// Array( [0] => token0, [1] => token1, [2] => token2, etc );
    
31.07.2017 / 13:04