6

I have the following array $foo

array(10) {
[0] => array(4) {

["merchantId"] => string(5) "12e21"
["programId"] => string(27) "ddd3333"
["networkId"] => int(4)
["clientId"] => int(178)
}
[1] => array(4) {

["merchantId"] => string(5) "112e1"
["programId"] => string(27) "2vfrdbv1&=10&tmfdpid=csss"
["networkId"] => int(4)
["clientId"] => int(178)
}
[2] => array(4) {

["merchantId"] => string(5) "112e1"
["programId"] => string(27) "2vfrdbv1&=10&tmfdpid=csss"
["networkId"] => int(4)
["clientId"] => int(178)
}

And I need an array of clientId's (only)

Is it possible to access just the clientId to create an array of id's without a loop?

Something like:

$foo['clientId']; //which doesn't work
Fluffeh
  • 33,228
  • 16
  • 67
  • 80
David Sigley
  • 1,126
  • 2
  • 13
  • 28
  • PHP 5.5's new array_column() function is used for precisely this purpose: There's a version of this function that can work with earlier versions available from https://github.com/ramsey/array_column – Mark Baker Sep 13 '13 at 11:14

2 Answers2

15

In PHP 5.5:

$rgResult = array_column($foo, 'clientId');

in PHP <=5.5:

$rgResult = array_map(function($rgItem)
{
  return $rgItem['clientId'];
}, $foo);

(put <= since this, of cause, will work in 5.5 too)

Ashwini Agarwal
  • 4,828
  • 2
  • 42
  • 59
Alma Do
  • 37,009
  • 9
  • 76
  • 105
  • @AlmaDoMundo - nothing I meant this please check it. http://stackoverflow.com/questions/19634429/how-to-truncate-this-and-make-it-a-link/19634528#19634528 – Sina R. Oct 28 '13 at 12:37
  • So what this question is to do with that? As do I? – Alma Do Oct 28 '13 at 12:39
0

As an alternative to array_column()

$transpose = call_user_func_array(
    'array_map',
    array_merge(
        array(NULL),
        $data
    )
);
$result = $transpose[array_search("programId", array_keys($data[0]))];
var_dump($result);

Which can be done as a one-liner in PHP5.5

$result = call_user_func_array('array_map',array_merge(array(NULL),$data))[array_search("programId", array_keys($data[0]))];
var_dump($result);

I'll confess, it's not exactly intuitive or readable though

Mark Baker
  • 209,507
  • 32
  • 346
  • 385