PHP:重新排序关联数组 [英] PHP: re order associative array

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

问题描述

在php中,我希望能够通过将元素移动到数组中的某些位置来重新排序关联数组.不必排序,只需重新排序即可.

In php, I would like to have the ability to re-order an associative array by moving elements to certain positions in the array. Not necessary a sort, just a re-ordering of my choosing.

作为一个例子,假设我有一个如下的关联数组:

As an example, say i have an associative array as follows:

array(
 'a' => 'Element A',
 'b' => 'Element B',
 'c' => 'Element C',
);

在一种情况下,我可能想将C移到B之前,并得到以下结果:

and in one case i may want to move C before B and have the following result:

array(
 'a' => 'Element A',
 'c' => 'Element C',
 'b' => 'Element B',
);

或者在另一种情况下,我可能想将C移到A之前并得到以下结果:

or in another case i may want to move C before A and have the following result:

array(
 'c' => 'Element C',
 'a' => 'Element A',
 'b' => 'Element B',
);

我要显示的只是一种方法,它说:嘿,我想将此数组元素移到另一个数组元素之前"或嘿,id喜欢移动此数组元素以确保它在之后另一个数组元素'

What i am trying to show, is simply a method for saying "Hey, i want to move this array element before this other array element" or "Hey, id like to move this array element to make sure that it comes after this other array element'

希望这是有道理的!

在此先感谢任何愿意帮助我的人

Thank you to anyone in advance who cares to help me with this

推荐答案

如果您打算交换两个值,则可以创建如下函数:

If you mean to swap two values you could make a function like this:

function array_swap($key1, $key2, $array) {
        $newArray = array ();
        foreach ($array as $key => $value) {
            if ($key == $key1) {
                $newArray[$key2] = $array[$key2];
            } elseif ($key == $key2) {
                $newArray[$key1] = $array[$key1];
            } else {
                $newArray[$key] = $value;
            }
        }
        return $newArray;
    }

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

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