PHP:将关联数组元素移动到数组的开头 [英] PHP: Move associative array element to beginning of array

查看:157
本文介绍了PHP:将关联数组元素移动到数组的开头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将关联数组的任何元素移到数组开头的最佳方法是什么?

What would be the best method of moving any element of an associative array to the beginning of the array?

例如,说我有以下数组:

For example, say I have the following array:

$myArray = array(
    'two'   => 'Blah Blah Blah 2',
    'three' => 'Blah Blah Blah 3',
    'one'   => 'Blah Blah Blah 1',
    'four'  => 'Blah Blah Blah 4',
    'five'  => 'Blah Blah Blah 5',
);

我想做的是将'one'元素移到开头并以以下数组结尾:

What i want to do is move the 'one' element to the beginning and end up with the following array:

$myArray = array(
    'one'   => 'Blah Blah Blah 1',
    'two'   => 'Blah Blah Blah 2',
    'three' => 'Blah Blah Blah 3',
    'four'  => 'Blah Blah Blah 4',
    'five'  => 'Blah Blah Blah 5',
);

推荐答案

您可以使用数组联合运算符(+)通过已知键(one)将原始数组连接到新的关联数组. /p>

You can use the array union operator (+) to join the original array to a new associative array using the known key (one).

$myArray = array('one' => $myArray['one']) + $myArray;
// or      ['one' => $myArray['one']] + $myArray;

阵列键是唯一的,因此不可能在两个位置都存在.

请参阅php.net/manual/en/language.operators.array.php:

Please see php.net/manual/en/language.operators.array.php:

+运算符返回添加到左侧数组的右侧数组;对于两个数组中都存在的键,将使用左侧数组中的元素,而右侧数组中的匹配元素将被忽略.

The + operator returns the right-hand array appended to the left-hand array; for keys that exist in both arrays, the elements from the left-hand array will be used, and the matching elements from the right-hand array will be ignored.

这篇关于PHP:将关联数组元素移动到数组的开头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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