How can I get an array of one type from a multidimensional array (without a loop)

I have the following $ foo array

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 a clientId array (only)

Is it possible to access only clientId to create an id array without a loop?

Sort of:

 $foo['clientId']; //which doesn't work 
+6
source share
2 answers

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, due to a reason, will work in 5.5 as well)

+15
source

Alternatively 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); 

What can be done as a single line 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 admit, this is not entirely intuitive or readable, although

0
source

Source: https://habr.com/ru/post/953770/


All Articles