notes icon indicating copy to clipboard operation
notes copied to clipboard

将PHP关联数组的某个元素移动到数组开始位置 or PHP Move associative array element to beginning of array

Open lanlin opened this issue 7 years ago • 0 comments

场景

某些时候,我们需要将关联数组中的某个元素排列到第一的位置。 比如,数据库查询条件的拼装。为了优化性能,往往需要调整条件的过滤顺序。 使其优先命中被索引的字段。

方法

假定zzz是目标索引, 下面将 zzz 调整到数据开始位置。

$temp =
[
    'xyz' => 'val 1',
    'xxx' => 'val 2',
    'zzz' => 'val 3',
];

$newArr = ['zzz' => $temp['zzz']] + $temp;

print_r($newArr);

// 以下是最终结果
// $newArr =
// [
//     'zzz' => 'val 3',
//     'xyz' => 'val 1',
//     'xxx' => 'val 2',
// ];

lanlin avatar Nov 23 '18 10:11 lanlin