gpt4 book ai didi

PHP:将关联数组元素移动到数组的开头

转载 作者:IT老高 更新时间:2023-10-28 11:55:54 26 4
gpt4 key购买 nike

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

例如,假设我有以下数组:

$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',
);

我想要做的是将“一个”元素移动到开头并以以下数组结束:

$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) 将原始数组连接到新的关联数组。

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

数组键是唯一的,所以它不可能同时存在于两个位置。

请参阅文档 on Array Operators:

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:将关联数组元素移动到数组的开头,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11276313/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com