John Default
John Default

Reputation: 51

Get specific key value pair from multidimensional array

I have the following array:

array(2) {
  [0] => array(3) {
    ["submission_id"] => int(28)
    ["date"] => string(22) "2010-10-18 15:55:33+02"
    ["user_id"] => int(12)
  }
  [1] => array(3) {
    ["submission_id"] => int(37)
    ["date"] => string(22) "2010-11-21 16:02:07+01"
    ["user_id"] => int(23)
  }

I want to get only the user_id key values from this array. I could obviously loop over it, but I was wondering if there was a quicker way.

Upvotes: 5

Views: 11400

Answers (2)

Felix Kling
Felix Kling

Reputation: 816840

You could use array_map (might not be quicker though, as it will make a function call per array element):

function getUserId($a) {
    return $a['user_id'];
}

$user_ids = array_map('getUserId', $array);

Apart from that, looping is the only way (array_map makes loop anyway).

Upvotes: 17

Rihards
Rihards

Reputation: 10349

You can access only the user_id values like this if you know the array index you want to access:

$arr = your array here..
echo $arr[0]['user_id'];
echo $arr[1]['user_id'];

Upvotes: -3

Related Questions