php 用php交换数组值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11298251/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 00:12:41  来源:igfitidea点击:

Swap array values with php

phparrays

提问by Sergio Toledo Piza

I have an array:

我有一个数组:

array(
    0 => 'contact',
    1 => 'home',
    2 => 'projects'
);

and I need to swap the 'contact' with 'home', so the array would be like:

我需要将“联系人”与“家”交换,因此数组将如下所示:

array(
    0 => 'home',
    1 => 'contact',
    2 => 'projects'
);

how can I do this with PHP? :)

我怎样才能用 PHP 做到这一点?:)

回答by voodoo417

I wrote simple function array_swap: swap two elements between positions swap_a& swap_b.

我写了一个简单的函数array_swap:在位置swap_a&之间交换两个元素swap_b

function array_swap(&$array,$swap_a,$swap_b){
   list($array[$swap_a],$array[$swap_b]) = array($array[$swap_b],$array[$swap_a]);
}

For OP question (for example):

对于 OP 问题(例如):

$items = array(
  0 => 'contact',
  1 => 'home',
  2 => 'projects'
);

array_swap($items,0,1);
var_dump($items);
// OUTPUT

array(3) {
   [0]=> string(4) "home"
   [1]=> string(7) "contact"
   [2]=> string(8) "projects"
 }

UpdateSince PHP 7.1 it's possible to do it like:

更新自 PHP 7.1 起,可以这样做:

$items = [
  0 => 'contact',
  1 => 'home',
  2 => 'projects'
];

[$items[0], $items[1]] = [$items[1], $items[0]];

var_dump($items);
// OUTPUT

array(3) {
   [0]=> string(4) "home"
   [1]=> string(7) "contact"
   [2]=> string(8) "projects"
 }

It's possible through Symmetric array destructuring.

可以通过对称数组解构来实现

回答by PriestVallon

Try this:

尝试这个:

$a = array(
    0 => 'contact',
    1 => 'home',
    2 => 'projects'
);
$temp = $a[0];
$a[0] = $a[1];
$a[1] = $temp;

回答by sachleen

Just use a temp variable to hold one value as you swap the other. Then restore the first with the temp variable. For numbers there are other methodsthat don't require the use of temp variables but here it's the best (only?) way.

在交换另一个值时,只需使用临时变量来保存一个值。然后用临时变量恢复第一个。对于数字,还有其他方法不需要使用临时变量,但这是最好的(唯一的?)方法。

$a = array(
    0 => 'contact',
    1 => 'home',
    2 => 'projects'
);

print_r($a);
Array ( [0] => contact [1] => home [2] => projects )

$tmp = $a[0];
$a[0] = $a[1];
$a[1] = $tmp;

print_r($a);
Array ( [0] => home [1] => contact [2] => projects )

回答by Brian Leishman

In PHP 7.1+ syntax, you can use this

在 PHP 7.1+ 语法中,你可以使用这个

[$Array[$a], $Array[$b]] = [$Array[$b], $Array[$a]];

回答by mickmackusa

New answer: (as others have expressed)

新答案:(正如其他人所表达的那样)

I was not aware of Symmetric Array Destructuring at the time of posting, but that is a functionless, one-liner swapping technique -- I'd use that all day long.

在发布时我不知道对称数组解构,但这是一种无功能的单行交换技术——我会整天使用它。

A relevant blog post/tutorial. An example implemention for bubble sorting.

一个相关的博客文章/教程冒泡排序示例实现

Code: (Demo)

代码:(演示

$a = ['contact', 'home', 'projects'];

[$a[0], $a[1]] = [$a[1], $a[0]];

var_export($a);


Old answer:

旧答案:

If you want to avoid using temporary data storage, or love a one-liner use array_replace().

如果你想避免使用临时数据存储,或者喜欢单行使用array_replace().

array_replace()will make adjustments in accordance with the indices:

array_replace()将根据指数进行调整:

Code: (Demo)

代码:(演示

$a = array(
    0 => 'contact',
    1 => 'home',
    2 => 'projects'
);

var_export(array_replace($a,[$a[1],$a[0]]));

Output:

输出:

array (
  0 => 'home',
  1 => 'contact',
  2 => 'projects',
)

回答by Andy

Just use a temp variable to hold it. So:

只需使用一个临时变量来保存它。所以:

$temp = $array[0];
$array[0] = $array[1];
$array[1] = $temp;

That way you don't lose the value of one of them.

这样你就不会失去其中之一的价值。

回答by rodneyrehm

$array = array(
    0 => 'home',
    1 => 'contact',
    2 => 'projects'
);

$t = $array[0];
$array[0] = $array[1];
$array[1] = $t;

would be a simple enough approach…

将是一个足够简单的方法......

回答by Lode Michels

$x = array('a', 'b', 'c', 'd');
array_splice($x, 1, 2, array_reverse(array_slice($x, 1, 2)));
var_dump($x);

array_splice can replace a reversed array_slice

array_splice 可以替换反向的 array_slice

回答by Guja1501

Solution:

解决方案:

$a = array(
    0 => 'contact',
    1 => 'home',
    2 => 'projects'
);

list($a[0], $a[1]) = [$a[1], $a[0]];

list($a[0], $a[1]) = [$a[1], $a[0]];

I have made function for it

我已经为它做了功能

function swap(&$a, &$b){
    list($a, $b) = [$b, $a];
}

Usage:

用法:

swap($a[0], $a[1]);

swap($a[0], $a[1]);

回答by Leopoldo Sanczyk

I tested the 4 ways proposed to compare the performance:

我测试了建议的 4 种比较性能的方法:

$array=range(0,9999); //First 10000 natural numbers
$time=-microtime(true); //Start time
for($i=0;$i<1000000;++$i){ //1 Millon swaps
    $a=array_rand($array); //Random position: ~60ms
    $b=array_rand($array); //Random position: ~60ms
    //Using a temp variable: ~70ms
    $temp=$array[0];$array[0]=$array[1];$array[1]=$temp;
    //Using list language construct: ~ 140ms
    list($array[$a],$array[$b])=array($array[$b],$array[$a]);
    //Using PHP 7.1+ syntax: ~ 140ms
    [$array[$a],$array[$b]]=[$array[$b],$array[$a]];
    //Using array_replace function: ~ 28000ms
    array_replace($array,[$array[$a],$array[$b]]);
}
$time+=microtime(true); //Elapsed time
echo "Time: ",sprintf('%f', $time)," seconds";

Although it is probably not the most comfortable way, using a temporary variable seems to be 2xfaster than the next 2 methods, and 400xfaster than using the array_replacefunction.

虽然它可能不是最舒适的方式,用一个临时变量似乎是2倍快于未来2种方法和400X比使用更快array_replace功能。