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

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

问题描述

可以说我有此数组:

$阵列=阵列('A'=大于1,'Z'=> 2,'D'=> 4);

在后来的剧本,我想添加值'C'=> 3 'Z'。我怎样才能做到这一点?

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()

编辑2:我上面使用的键是占位符。使用kso​​rt()不会达到我想要的。

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

编辑3:<一href=\"http://www.php.net/manual/en/function.array-splice.php#88896\">http://www.php.net/manual/en/function.array-splice.php#88896完成我正在寻找,但我在寻找简单的东西。

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

编辑4:感谢您的downvotes。我给反馈给你答案,你不能帮助,让你downvoted,并要求关闭的问题,因为你不知道答案。谢谢你。

EDIT 4: Thanks for the downvotes. I gave feedback to your answers and you couldn't help, so you downvoted and requested to close the question because you didn't know the answer. Thanks.

编辑5:取一个样本数据库表约30列。我得到这个数据使用mysql_fetch_assoc()。在这个新阵,列'比萨'和'喝'后,我想补充一点,结合了比萨和喝的值的新列full_dinner所以,当我在所述阵列上运行的foreach() full_dinner直接喝

EDIT 5: 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)
        );


不存在键的处理(追加 $数据默认情况下):

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天全站免登陆