PHP - get multiple columns from array

后端 未结 7 1845
星月不相逢
星月不相逢 2021-01-12 09:55

I have this array:

0 => array:3 [
    \"product_id\" => \"1138\"
    \"product_image\" => \"/resources/medias/shop/products/shop-6500720--1.png\"
           


        
相关标签:
7条回答
  • 2021-01-12 10:39

    An added feature to the array_columns function that eventually traces back to Chayan's answer, this time extended from Joseph Mangion's function.

    I occasionally have long lists of the selected columns where I want to preserve the keys and don't necessarily want to follow the cumbersome ['orignal_field_name'] => ['original_field_name'] format for a great number of fields.

    This version preserves the original key for each field by default unless a new key is specified.

    // See answer from Joseph Mangion: https://stackoverflow.com/questions/52706383/php-get-multiple-columns-from-array
    /** Function - array_columns  Selects columns from multidimensional array and renames columns as required
    *
    * @param  array $in_array, array $select_columns_rename_keys
    *   example of $select_columns_rename_keys:
    *       ['new_column_name1' => 'original_column_name1', 'original_column_name2', 'original_column_name3', 'new_column_name4' => 'original_column_name4', ...]
    *       This will use the original keys for columns 2 and 3 and rename columns 1 and 4
    * @return array
    * @access public
    * 
    */   
    
    public function array_columns($in_array, $select_columns_rename_keys) {
        foreach ($select_columns_rename_keys as $k => $v)
            if (is_int($k)) {
                $select_columns_rename_keys[$v] = $v;
                unset($select_columns_rename_keys[$k]);
            }
        $keys = array_flip($select_columns_rename_keys);
        $filtered_array =
            array_map(function($a) use($keys) {
            $data = array_intersect_key($a, $keys);
            $return_array = [];
            foreach ($data as $column_name => $value) $return_array[$keys[$column_name]] = $value;
            return $return_array;
        }, $in_array);
    
        return $filtered_array;
    }
    
    0 讨论(0)
提交回复
热议问题