Is there a function to extract a 'column' from an array in PHP?

前端 未结 14 1388
鱼传尺愫
鱼传尺愫 2020-11-21 07:33

I have an array of arrays, with the following structure :

array(array(\'page\' => \'page1\', \'name\' => \'pagename1\')
      array(\'page\' => \'pa         


        
14条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-21 07:53

    Well there is. At least for PHP > 5.5.0 and it is called array_column

    The PHP function takes an optional $index_keyparameter that - as per the PHP website - states:

    $index_key

    The column to use as the index/keys for the returned array. This value may be the integer key of the column, or it may be the string key name

    In the answers here, i see a stripped version without the optional parameter. I needed it, so, here is the complete function:

    if (!function_exists('array_column')) {
        function array_column($array, $column, $index_key = null) {
            $toret = array();
            foreach ($array as $key => $value) {
                if ($index_key === null){
                    $toret[] = $value[$column];
                }else{
                    $toret[$value[$index_key]] = $value[$column];
                }
            }
            return $toret;
        }
    }
    

提交回复
热议问题