如何将数组值添加到关联数组的中间? [英] How to add an array value to the middle of an associative array?

查看:39
本文介绍了如何将数组值添加到关联数组的中间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有这个数组:

$array = array('a'=>1,'z'=>2,'d'=>4);

在脚本的后面,我想在 'z' 之前添加值 'c'=>3.我该怎么做?

Later in the script, I want to add the value 'c'=>3 before 'z'. How can I do this?

是的,顺序很重要.当我通过数组运行 foreach() 时,我不希望将此新添加的值添加到数组的末尾.我从 mysql_fetch_assoc() 获取这个数组

Yes, the order is important. When I run a foreach() through the array, I do NOT want this newly added value added to the end of the array. I am getting this array from a mysql_fetch_assoc()

我上面使用的键是占位符.使用 ksort() 不会达到我想要的效果.

The keys I used above are placeholders. Using ksort() will not achieve what I want.

http://www.php.net/manual/en/function.array-splice.php#88896 完成了我正在寻找的东西,但我正在寻找更简单的东西.

http://www.php.net/manual/en/function.array-splice.php#88896 accomplishes what I'm looking for but I'm looking for something simpler.

以大约 30 列的示例数据库表为例.我使用 mysql_fetch_assoc() 获取这些数据.在这个新数组中,在列 'pizza' 和 'drink' 之后,我想添加一个新列 'full_dinner',它结合了 'pizza' 和 'drink' 的值,这样当我在上述数组上运行 foreach() 时, 'full_dinner' 紧跟在 'drink' 之后

Take a sample db table with about 30 columns. I get this data using mysql_fetch_assoc(). In this new array, after column 'pizza' and 'drink', I want to add a new column 'full_dinner' that combines the values of 'pizza' and 'drink' so that when I run a foreach() on the said array, 'full_dinner' comes directly after 'drink'

推荐答案

我是否遗漏了什么?

$key = 'z';
$offset = array_search($key, array_keys($array));

$result = array_merge
        (
            array_slice($array, 0, $offset),
            array('c' => 3),
            array_slice($array, $offset, null)
        );

<小时>

处理不存在的键(默认附加$data):

function insertBeforeKey($array, $key, $data = null)
{
    if (($offset = array_search($key, array_keys($array))) === false) // if the key doesn't exist
    {
        $offset = 0; // should we prepend $array with $data?
        $offset = count($array); // or should we append $array with $data? lets pick this one...
    }

    return array_merge(array_slice($array, 0, $offset), (array) $data, array_slice($array, $offset));
}

演示:

$array = array('a' => 1, 'z' => 2, 'd' => 4);

// array(4) { ["a"]=> int(1) ["c"]=> int(3) ["z"]=> int(2) ["d"]=> int(4) }
var_dump(insertBeforeKey($array, 'z', array('c' => 3)));

// array(4) { ["a"]=> int(1) ["z"]=> int(2) ["d"]=> int(4) ["c"]=> int(3) }
var_dump(insertBeforeKey($array, 'y', array('c' => 3)));

这篇关于如何将数组值添加到关联数组的中间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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