Foreach within Foreach PHP

Asked

Viewed 838 times

4

I have the following code:

$row = $twitterusers->selectUserAll();

foreach ($row as $fetch) {
    $users[] = $fetch;
}

var_dump($users);

It takes all users from the table, but when using the var_dump I understand you have array inside array, see:

0 => 
    array (size=6)
      'id' => string '1' (length=1)
      'user_id' => string '123' (length=18)
      'screen_name' => string 'login1' (length=13)
      'oauth_token' => string 'token-hash' (length=50)
      'oauth_token_secret' => string 'token-hash2' (length=45)
      'vip' => string '0' (length=1)
  1 => 
    array (size=6)
      'id' => string '2' (length=1)
      'user_id' => string '1234' (length=18)
      'screen_name' => string 'login2' (length=12)
      'oauth_token' => string 'token-hash' (length=50)
      'oauth_token_secret' => string 'token-hash2' (length=45)
      'vip' => string '0' (length=1)

I wanted to get all the users_id, but I’m not getting, example:

Instead of 0 => and 1 =>, I would like you to stay all in one array, how can I do this?

Note: print all ids as follows:

user_id => 123
user_id => 1234
user_id => 1235
user_id => 1236

1 answer

5


You can do it like this:

$fetch = $twitterusers->selectUserAll();

foreach ($fetch as $row) {
    $usersIds[] = $row['id'];
}

var_dump($usersIds);

Or better yet, without having to iterate with array_column:

$fetch = $twitterusers->selectUserAll();

$userIds = array_column($fetch, 'id');

var_dump($usersIds);
  • 1

    Oops, it worked, and I did it this way because it doesn’t work I don’t know. I’ll wait to give you the time you’re asking to mark as solved, vlw thanks gmsantos.

  • even worked, but wanted to join these id’s all in one example array: 0 => id1, id,2 id,3 would have like ?

  • 1

    But that’s it q it is hj, each key of that array is an id that you iterate and see the result of each. It is not a multidimensional array, as you want it to be.

  • understand, is that it is not working all id’s, only 3 works. but I will try to fix.

Browser other questions tagged

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