php array_merge关联数组 [英] php array_merge associative arrays

查看:93
本文介绍了php array_merge关联数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将一个项目添加到关联数组的开头.我认为最好的方法是使用array_merge,但结果有些奇怪.我从mysql数据库中获取了产品的ID和产品名称,并以关联数组的形式返回了该数据(不是返回实际数据,而是该问题的示例数据,表示该数据大致看起来像什么):

I'm trying to prepend an item to the beginning of an associative array. I figured the best way to do this is to use array_merge, but I'm having some odd consequences. I get the id and Name of products from a mysql database, and it gets returned as an associative array, like this (not the actual data coming back, but sample data for this question that represents what the data looks like approximately):

$products = array (1 => 'Product 1', 42 => 'Product 42', 100 => 'Product 100');

这将被发送到html帮助器以创建一个将键与值相关联的下拉列表,并且数组项的值将被设置为下拉选择控件中的文本.我需要第一个项目是一个类似请选择"的键,其键为0,所以我这样做了:

this is getting sent to an html helper to create a dropdown that associates the key with the value, and the value of the array item gets set as the text in the drop down select control. I need the first item to be something like "Please Select" with a key of 0, so I did this:

$products = array_merge(array(0 => "Select a product" ), $products);

结果数组如下:

array(
  0 => 'Select a product', 
  1 => 'Product 1', 
  2 => 'Product 42', 
  3 => 'Product 100' 
);

当我真正想要的是不丢失关联数组的键时.有人告诉我您可以按照尝试的方式将array_merge与关联数组一起正确使用,但是,我相信,因为我的键是 ints ,所以它没有将数组视为真正的关联数组,而是对其进行了压缩如上图所示.

when What I really wanted was not to lose the keys of the associative array. I was told that you can properly use array_merge with associative arrays in the manner I tried, however, I believe because my keys are ints that it is not treating the array as a true associative array, and compressing them as illustrated above.

问题是:为什么array_merge函数更改项的键?我可以阻止它这样做吗?还是我还有另一种方法可以完成我想做的事情,即在数组的开头添加新项?

The question is: Why is the array_merge function changing the keys of the items? can I keep it from doing this? OR is there another way for me to accomplish what I'm trying to do, to add the new item at the beginning of the array?

推荐答案

来自文档:

如果要在不覆盖第一个数组中的元素且不重新索引的情况下将第二个数组中的数组元素追加到第一个数组,请使用+数组联合运算符

If you want to append array elements from the second array to the first array while not overwriting the elements from the first array and not re-indexing, use the + array union operator

使用+联合运算符时,将保留第一个数组参数的键,因此,反转参数的顺序并使用联合运算符应满足您的要求:

The keys from the first array argument are preserved when using the + union operator, so reversing the order of your arguments and using the union operator should do what you need:

$products = $products + array(0 => "Select a product");

这篇关于php array_merge关联数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆