0

i have array given below

 Array ( 
       [0] => Array ( 
                    [user_id] => 2 
                    )
       [1] => Array (
                    [user_id] => 4 
                    )
       )

i need to select these user id to fetch data from database and display in html table i tried this

foreach($prevUser as $key => $value){

        print_r($value);
    }

and receive this not the values

Array ( [user_id] => 2 ) Array ( [user_id] => 4 )

how to get user id

1
  • use echo echo $value['user_id']; instead of print_r($value); Commented Apr 15, 2017 at 6:09

3 Answers 3

2

You can get the user like below and fire queries using two ways first is.

foreach($prevUser as $key => $value){
    $user_id = $value['user_id'];
    //write your query here like "select * from user where id = $user_id";
    print_r($value);
}

the second and proper way is

$userIds = [];
foreach($prevUser as $key => $value){
    $userIds[] = $value['user_id'];
}

// stores all user_id on single array and then fire query like below

//write your query here like "select * from user where id IN $userIds";

I prefer to used second way instead of first way. I hope this is help full for you

Sign up to request clarification or add additional context in comments.

2 Comments

but how could i loop userids now
You don't need to create the loop for userids. just fire query directly without using loop like "select * from user where id IN $userIds".
0

You can use $user_ids = array_column($prevUser, 'user_id');

$user_ids is an array of user_id like this [2, 4], then you can traverse it with foreach like this,

foreach($user_ids as $user_id)
{
  echo $user_id;
}

Comments

-1
<?php
$array = Array(
    0 => Array(
        user_id => 2
    ),
    1 => Array(
        user_id => 4
    )
);
foreach ($array as $key => $value) {
    $user_id = $value['user_id'];
    echo $user_id;
    echo "<br>";
}
?>

2 Comments

You answer should be more than just code, please edit and explain your answer
here firstly the correct way to declare the array and fetching the data using the foreach loop,

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.