php关联数组键顺序(不排序) [英] php associative array key order (not sort)

查看:59
本文介绍了php关联数组键顺序(不排序)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的数组:

$data = array('two' => 2, 'one' => 1, 'three' => 3);

现在,当我迭代数组时,出现的第一个值可能是

Now, with when I iterate the array, the first value that will come up will probably be

$data['two'] // = 2 @ index[0]

对吧?

如果我想把 $data[1] 移动到 $data[0] 的位置怎么办?

What if I want to move the $data[1] to the position of $data[0] ?

改写:

如何使数组看起来像这样(以便在 $data[0] 处出现one")

How do I make the array look like this (so that 'one' comes up at $data[0])

$data = array('one' => 1, 'two' => 2, 'three' => 3

我为什么需要这个?

我使用代码点火器,table->generate 内置函数接受一个 assoc 数组并创建一个表,但没有提供排列列的方法.这就是为什么我想移动源数组中的列.

I use code igniter, the table->generate built-in function takes an assoc array and creates a table but offers no method of arranging the columns. This is why I would like to move the columns in the source array.

推荐答案

看一看 daniele centamore 对 PHP 的的评论array_splice() 函数,他提供了几个函数来移动非关联数组中的元素.

Take a look at daniele centamore's comment on PHP's array_splice() function, where he provides a couple of functions for moving the elements in an non-associative array.

<?php

// $input  (Array) - the array containing the element
// $index (int) - the index of the element you need to move

function moveUp($input,$index) {
      $new_array = $input;

       if((count($new_array)>$index) && ($index>0)){
                 array_splice($new_array, $index-1, 0, $input[$index]);
                 array_splice($new_array, $index+1, 1);
             } 

       return $new_array;
}

function moveDown($input,$index) {
       $new_array = $input;

       if(count($new_array)>$index) {
                 array_splice($new_array, $index+2, 0, $input[$index]);
                 array_splice($new_array, $index, 1);
             } 

       return $new_array;
}  

$input = array("red", "green", "blue", "yellow");

$newinput = moveUp($input, 2);
// $newinput is array("red", "blue", "green", "yellow")

$input = moveDown($newinput, 1);
// $input is array("red", "green", "blue", "yellow")

?>

这篇关于php关联数组键顺序(不排序)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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