如何将一个键数组与另一个数组中的相应值组合起来?
我有2个数组
Array ( [1] => Manufacturer [2] => Location [3] => Hours [4] => Model )
我
Array ( [Manufacturer] => John Deere [Location] => NSW [Hours] => 6320 )
需要将它们组合起来并将第一个数组(制造商、位置、小时、型号)中的值关联为第二个数组中的名称,并且如果第一个数组中的特定值在第二个数组中找不到要关联的关联名称空的 。对于示例,我需要从上面的数组得到的结果是这样的数组
Array ( [Manufacturer] => John Deere [Location] => NSW [Hours] => 6320 [Model] => )
如果我使用简单的 array_combine 它会说 PHP警告:array_combine()[function.array-combine]:两个参数应该具有相同数量的元素
I have 2 arrays
Array ( [1] => Manufacturer [2] => Location [3] => Hours [4] => Model )
and
Array ( [Manufacturer] => John Deere [Location] => NSW [Hours] => 6320 )
I need to combine them and associate the values from the first array( Manufacturer, Location, hours , Model) as names in the 2nd array and if a specific values from the first array doesn't find associative name in the 2nd array to associate empty . For the example the result that I need from the above arrays is an array like this
Array ( [Manufacturer] => John Deere [Location] => NSW [Hours] => 6320 [Model] => )
If i use simple array_combine it says that PHP Warning: array_combine() [function.array-combine]: Both parameters should have equal number of elements
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以使用简单的
foreach
循环:其中
$keys
是包含键的第一个数组,$values
是包含相应值的第二个数组。如果$values
中没有对应的值,则该值为null
。You can use a simple
foreach
loop:Where
$keys
is your first array with the keys and$values
is your second array with the corresponding values. If there is no corresponding value in$values
the value will benull
.假设 $array1 和 $array2 按照您列出的顺序排列,我认为这会起作用:
Assuming $array1 and $array2 in order as you listed them, I think this would work:
尝试
array_merge()
。这个例子似乎做了你想做的事:Try
array_merge()
. This example appears to do what you want:如果键数组是 $array1,并且具有值的关联数组是 $array2:
这会反转您的键数组,并用 '' 值填充它。然后,当您合并数组时,任何重复的键都将被第二个数组覆盖,但未填充的键将保留。
If the array of keys is $array1, and the associative array with values is $array2:
This inverts your key array, filling it with '' values. Then when you merge the arrays, any duplicate keys will be overwritten by the second array, but unfilled keys will remain.