PHP关联数组重复键 [英] PHP Associative Array Duplicate Keys

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

问题描述

我有一个关联数组,但是当我使用以下函数向其添加值时,它似乎会覆盖相同的键.有没有办法让多个相同的键具有不同的值?还是有另一种格式的数组具有相同的格式?

I have an associative array, however when I add values to it using the below function it seems to overwrite the same keys. Is there a way to have multiple of the same keys with different values? Or is there another form of array that has the same format?

我想要拥有:

42=>56
42=>86
42=>97
51=>64
51=>52
etc etc

代码:

   function array_push_associative(&$arr) {
       $args = func_get_args();
       foreach ($args as $arg) {
           if (is_array($arg)) {
               foreach ($arg as $key => $value) {
                   $arr[$key] = $value;
                   $ret++;
               }
           }else{
               $arr[$arg] = "";
           }
       }
       return $ret;
    }

推荐答案

否,关联数组中不能有多个相同的键.

No, you cannot have multiple of the same key in an associative array.

但是,您可以具有唯一的键,每个键的对应值都是数组,并且这些数组的每个键都有多个元素.

You could, however, have unique keys each of whose corresponding values are arrays, and those arrays have multiple elements for each key.

所以代替这个...

42=>56 42=>86 42=>97 51=>64 51=>52

...你有这个:

Array (
    42 => Array ( 56, 86, 97 )
    51 => Array ( 64, 52 )
)

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

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