移动键/值在键控PHP数组 [英] Moving Key/Values in a Keyed PHP Array

查看:164
本文介绍了移动键/值在键控PHP数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的数组:

I have an array like this:

array (size=8)
  'cb' => string '<input type="checkbox"/>' (length=24)
  'title' => string 'Name' (length=4)
  'download_category' => string 'Categories' (length=10)
  'download_tag' => string 'Tags' (length=4)
  'price' => string 'Price' (length=5)
  'sales' => string 'Sales' (length=5)
  **'earnings' => string 'Earnings' (length=8)**
  'shortcode' => string 'Purchase Short Code' (length=19)
  'date' => string 'Date' (length=4)

现在我想做的事情,就是移动的收入之一,像这样的第三位:

Now what I want to do, is move the 'earnings' one, to the third position like this:

array (size=9)
  'cb' => string '<input type="checkbox"/>' (length=24)
  'title' => string 'Name' (length=4)
  **'earnings' => string 'Earnings' (length=8)**
  'download_category' => string 'Categories' (length=10)
  'download_tag' => string 'Tags' (length=4)
  'price' => string 'Price' (length=5)
  'sales' => string 'Sales' (length=5)
  'shortcode' => string 'Purchase Short Code' (length=19)
  'date' => string 'Date' (length=4)

这个数组的第9个元素都是静态的,即顺序是固定的,但可能有更多的元素数组('日'后),如果该事项。

The first 9 elements of this array are static in the sense that the order is fixed, but there may be more elements to this array (after 'date') if that matters.

所以,我正在寻找一种简单的方法在当前的第三元素的位置的前方移动第x元素。

Therefore, I'm looking for an easy way to move the xth element in front of the current 3rd element's position.

一件事,我曾尝试在第一个2个元素保存到一个变量,那么unset它们。我也取消设置盈利元素给一个变量。因此,阵列再与第三个元素开始。然后,因为我希望我的未来元素的第三元素,我需要其他2个元素回,这样的:

One thing I have tried is saving the first 2 elements to a variable, then unsetting them. I also unset the earnings element to a variable. So the array then begins with the 3rd element. Then, since I want my element ahead of the 3rd element, and I need those other 2 elements back in, like this:

$first = $array[0];
$second = $array[1];
$earnings_element = $array['earnings'];
unset($array[0]); 
unset($array[1]);
unset($array['earnings']);
array_unshift($array,$first,$second,$earnings_element);

的问题是,无论是我失去元素名称(它成为1,2-密钥值等)或该元件插回到在不印字的值

The problem is that either I lose the element name (it becomes a key value of 1,2,etc) or the value of that elements inserted back in the unshift.

任何人都知道一个更简单的方法呢?

Anyone know of an easier method?

编辑:我使用的阵的名称在下面的code数组。它不是实际的数组的名称。

I am using "array" as the name for the array in the code below. Its not the name of the actual array.

推荐答案

试试这个:

$front = array_slice($array,0,2);
$front['earnings'] = $array['earnings'];
$back = array_slice($array,2);
unset($back['earnings']);
$array = array_merge($front,$back);

这篇关于移动键/值在键控PHP数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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