How can I get the array of a single type from a multi dimensional array (without a loop)

后端 未结 2 1976
伪装坚强ぢ
伪装坚强ぢ 2021-01-18 12:56

I have the following array $foo

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

[\"merchantId\"] => string(5) \"12e21\"
[\"programId\"] => string(27) \"ffffd3333\"
[\"         


        
相关标签:
2条回答
  • 2021-01-18 13:13

    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

    0 讨论(0)
  • 2021-01-18 13:24

    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)

    0 讨论(0)
提交回复
热议问题