我习惯于使用perl的map()函数,其中回调函数可以同时分配键和值,从而创建一个关联数组,其输入为平面数组。我知道array_fill_keys()
可以用于创建字典风格的哈希表,但如果您不一定希望所有值都相同怎么办?显然,所有事情都可以通过循环迭代来完成,但还有哪些(可能更优雅)的方法存在呢?
编辑:添加一个示例以澄清转换。请不要纠缠于转换,问题在于将扁平列表转换为哈希表,其中我们不能假定所有值都相同。
$original_array: ('a', 'b', 'c', 'd')
$new_hash: ('a'=>'yes', 'b'=>'no', 'c'=>'yes', 'd'=>'no')
*note: the values in this example are arbitrary, governed by some business logic that is not really relevant to this question. For example, perhaps it's based on the even-oddness of the ordinal value of the key
现实世界的例子 所以,使用这里提供的答案,您可以解析$_POST以获取只匹配给定条件的输入字段列表。例如,如果您的表单中有许多输入字段,但某个特定组必须一起处理,则这可能很有用。
在这种情况下,我有许多输入字段,它们表示到数据库的映射。每个输入字段看起来像这样:<input name="field-user_email" value="2" />
,其中每种类型的字段都已前缀为“field-”。
我们想要做的是首先获取仅以“field-”开头的那些输入字段的列表,然后我们想要创建一个名为$mapped_fields
的关联数组,其将提取的字段名称作为键,并将实际输入字段的值作为值。
$mapped_fields = array_reduce( preg_grep( '/field-.+/', array_keys( $_POST ) ), function( $hash, $field ){ $hash[substr( $field, 6 )] = $_POST[$field]; return $hash; } );
这将输出:
Array ( [date_of_birth] => 1 [user_email] => 2 [last_name] => 3 [first_name] => 4 [current_position] => 6 )
因此,为了预防那些持反对意见的人,让我同意这段紧凑代码可能比一个简单的循环遍历 $_POST 并且对于每个键检查是否具有前缀,并且如果是,则将它和它的值弹出到数组中的方法要不可读得多。
print_r
或var_dump
打印数组的内容? - Florent