我的PHP中有一个如下所示的数组:
$contacts = [
[
"name" => "Peter Parker",
"email" => "peterparker@mail.com",
], [
"name" => "Clark Kent",
"email" => "clarkkent@mail.com",
], [
"name" => "Harry Potter",
"email" => "harrypotter@mail.com"
]
];
如何交换最后一个元素和最后一个元素之前的元素?
答案 0 :(得分:2)
这应该这样做:
$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);