I have this array:
0 => array:3 [
\"product_id\" => \"1138\"
\"product_image\" => \"/resources/medias/shop/products/shop-6500720--1.png\"
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;
}