在 PHP 中交换多维数组



我的PHP中有一个数组,看起来像这样:

$contacts = [   
[   
"name" => "Peter Parker",    
"email" => "peterparker@mail.com",    
], [   
"name" => "Clark Kent",    
"email" => "clarkkent@mail.com",    
], [   
"name" => "Harry Potter",    
"email" => "harrypotter@mail.com"
] 
];

如何交换最后一个元素和最后一个元素之前的元素?

这应该可以做到:

$length = count($contacts);
$last = $contacts[$length - 1];
$before_last = $contacts[$length - 2];
// swap
$contacts[$length - 2] = $last;
$contacts[$length - 1] = $before_last;
//
var_dump($contacts);

或者另一种方式:

$last = array_pop($contacts);
$before_last = array_pop($contacts);
// swap
array_push($contacts, $last);
array_push($contacts, $before_last);
//
var_dump($contacts);

或者另一种方式:

// cut last 2
$temp = array_splice($contacts, -2);
// swap
array_push($contacts, $temp[1]);
array_push($contacts, $temp[0]);
//
var_dump($contacts);

最新更新