How to return array indices in method

Asked

Viewed 85 times

1

Well I couldn’t 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;
}

Look, I’m coming back $tokens that in case I could use so:

$tk = $users->select_tokens();

And then pick up the index:

$tk['user_token'];

or

$tk['user_token2'];

But I don’t know why this error returns to me:

Notice: Undefined index: user_token

or

Notice: Undefined index: user_token2

Obs: I want to take all tokens of all table users users.

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 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 main 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 so:

var_dump( $tokens['user_token'] );
// Array( [0] => token0, [1] => token1, [2] => token2, etc );
  • Yes, but he returns to me only 1 token in the case of the first ID, I want to catch the 10 it contains in the table. I tried this way.

  • I edited the answer to show how to get everyone in one key

  • Show, it’s what I wanted, it worked. Thanks.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.