在加入同一阵列中两个对之间的键/值对 [英] Add key/value pair in between two pairs in an array

查看:88
本文介绍了在加入同一阵列中两个对之间的键/值对的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在寻找和思考,但不能拿出一个可行的解决这个问题。

I have been looking and thinking, but can't come up with a viable solution to this problem.

我有序贯数字键数组

例如:

Array
 (
    [0] => value 0
    [1] => value 1
    [2] => value 2
    [3] => value 3
)

我要在我的数组添加一个新的键/值对两个特定键之间。

I need to add a new key/value pair in between two specific keys in my array.

例如:

我需要添加 [A] =>值键之间的 1 2

I need to add [a] => value a between keys 1 and 2 like

Array
 (
    [0] => value 0
    [1] => value 1
    [a] => value a
    [2] => value 2
    [3] => value 3
)

我已经这样做,虽然,但周围似乎很长的路要走。

What I already though of doing, but seems the long way around


  • 我切片阵列中的两个,我的键/值对添加到片之一的背部和重组我的2片成一个单一的阵列

  • slicing my array in two, add my key/value pair to the back of slice one, and recombine my 2 slices into a single array

一个莫名其妙地推进每个按键后按键 1 修改我的新的键/值对 [2] =>值时,将它添加到阵列的背面,然后再打我的数组

somehow advancing each key by one after key 1 modifying my new key/value pair to [2] => value a, the add it to the back of the array, and then resort my array

要快速清洁的方式任何建议,以实现这一目标。

Any suggestions to a quick clean way to achieve this

推荐答案

不知道为什么你会做...

Dont know why you will do it ...

    $array = array(0=>0,1=>1,2=>2,3=>3);

    $add = array('a'=>'a');

    $before_key = 2;

    $new_array = array();

    foreach($array as $key=>$val) {
        if($key===$before_key) {
            $new_array[key($add)] = $add[key($add)];
        }
        $new_array[$key] = $val;
    }
    $array = $new_array;
    var_dump($array);

这篇关于在加入同一阵列中两个对之间的键/值对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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