Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get specific key value pair from multidimensional array

Tags:

php

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.

like image 713
John Default Avatar asked Dec 29 '10 14:12

John Default


People also ask

How do you find the specific value of a key in an array?

The array_keys() function is used to get all the keys or a subset of the keys of an array. Note: If the optional search_key_value is specified, then only the keys for that value are returned. Otherwise, all the keys from the array are returned.

How do you find the element of a multidimensional array?

Multidimensional array search using array_search() method: The array_search() is an inbuilt function which searches for a given value related to the given array column/key. This function only returns the key index instead of a search path.

What is Array_keys () used for?

The array_keys() is a built-in function in PHP and is used to return either all the keys of and array or the subset of the keys. Parameters: The function takes three parameters out of which one is mandatory and other two are optional.


1 Answers

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).

like image 58
Felix Kling Avatar answered Sep 19 '22 11:09

Felix Kling