在 PHP 中交换多维数组

岩石

我的 PHP 中有一个数组,如下所示:

$contacts = [   
    [   
        "name" => "Peter Parker",    
        "email" => "[email protected]",    
    ], [   
        "name" => "Clark Kent",    
        "email" => "[email protected]",    
    ], [   
        "name" => "Harry Potter",    
        "email" => "[email protected]"
    ] 
];

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

这应该这样做:

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章