如何更改数组的顺序? [英] How to change orders of array?

查看:583
本文介绍了如何更改数组的顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

$a = array(0=>'a',1=>'b',2=>'c', 3=>'d');

我想将顺序更改为3,2,0,1:

$a = array(3=>'d',2=>'c',0=>'a', 1=>'b');

推荐答案

如果要以编程方式更改顺序,请查看各种

If you want to change the order programmatically, have a look at the various array sorting functions in PHP, especially

  • uasort()-使用用户定义的比较函数对数组进行排序并维护索引关联
  • uksort()-使用用户定义的比较功能按键对数组进行排序
  • usort()-使用用户定义的比较函数按值对数组进行排序
  • uasort()— Sort an array with a user-defined comparison function and maintain index association
  • uksort()— Sort an array by keys using a user-defined comparison function
  • usort()— Sort an array by values using a user-defined comparison function

基于下面的 Yannicks示例 ,您可以这样做:

Based on Yannicks example below, you could do it this way:

$a = array(0 => 'a', 1 => 'b', 2 => 'c', 3 => 'd');
$b = array(3, 2, 0, 1); // rule indicating new key order
$c = array();
foreach($b as $index) {
    $c[$index] = $a[$index];
}
print_r($c);

愿意给

Array([3] => d [2] => c [0] => a [1] => b)

但是,就像我在评论中说的那样,如果您不告诉我们订购数组的规则,或者更具体地了解您的需求,那么我们将无济于事.

But like I said in the comments, if you do not tell us the rule by which to order the array or be more specific about your need, we cannot help you beyond this.

这篇关于如何更改数组的顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆