php数组交换,php – 交换数组中的两个键/值对

标签:php

我有一个数组:

$array = array('a' => 'val1', 'b' => 'val2', 'c' => 'val3', 'd' => 'val4');

如何交换任意两个键,使阵列的顺序不同?例如.生成这个数组:

$array = array('d' => 'val4', 'b' => 'val2', 'c' => 'val3', 'a' => 'val1');

谢谢 :).

解决方法:

我以为现在会有一个非常简单的答案,所以我会把我扔进去:

// Make sure the array pointer is at the beginning (just in case)

reset($array);

// Move the first element to the end, preserving the key

$array[key($array)] = array_shift($array);

// Go to the end

end($array);

// Go back one and get the key/value

$v = prev($array);

$k = key($array);

// Move the key/value to the first position (overwrites the existing index)

$array = array($k => $v) + $array;

这是交换数组的第一个和最后一个元素,保留键.我原本以为你最初想要array_flip(),所以我希望我能正确理解.

标签:php

来源: https://codeday.me/bug/20190518/1126519.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值