重命名多维数组相关联的钥匙 [英] Renaming the keys in multidimensional associate arrays
问题描述
我已搜查SO和谷歌已经发现很多类似的问题,但没有适合我的确切使用情况。
I have searched SO and Google and have found lots of similar questions, but nothing that fits my exact use case.
我有数组这样的数组:
Array
(
[0] => Array
(
[id] => c80c5133-1140-8187-ad3b-524b4ed0f1a8
[date_entered] => 10/01/2013 03:38pm
)
[1] => Array
(
[id] => 176815c6-b57f-7643-0f08-524b4f22b51c
[date_entered] => 10/01/2013 03:42pm
)
[2] => Array
(
[id] => df0f8824-0b12-b92e-1d2e-524c6cb19c41
[date_entered] => 10/02/2013 11:56am
)
)
我需要重新命名的第一个维度的关键是在第二维数组像这样date_entered键的值,这样我可以(希望)阵列的最近日期排序。我需要preserve每个数组的内容,因为我需要抓住对应于正确的日期编号。
I need to rename the keys of the first dimension to be the value of the date_entered key in the second dimension arrays like this so that I can (hopefully) sort the array by the most recent date. I need to preserve the contents of each array because I will need to grab the ID that corresponds to the correct date.
Array
(
[10/01/2013 03:38pm] => Array
(
[id] => c80c5133-1140-8187-ad3b-524b4ed0f1a8
[date_entered] => 10/01/2013 03:38pm
)
[10/01/2013 03:42pm] => Array
(
[id] => 176815c6-b57f-7643-0f08-524b4f22b51c
[date_entered] => 10/01/2013 03:42pm
)
[10/02/2013 11:56am] => Array
(
[id] => df0f8824-0b12-b92e-1d2e-524c6cb19c41
[date_entered] => 10/02/2013 11:56am
)
)
我试图做这样的(这显然是不正确的),但我的生活我仍然不能得到它。
I am trying to do it like this (which is obviously not correct) but for the life of me I still can't get it.
foreach ($array as $key) {
foreach ($key as $subkey => $subvalue) {
if ($subkey == 'date_entered') {
// change the name of the key?
}
}
}
我真的多维数组挣扎,操纵他们,不管我读了多少和实践!谁能帮助?
I am really struggling with multidimensional arrays and manipulating them, no matter how much I read and practice! Can anyone help?
推荐答案
这code应该这样做:
This code should do it:
$newArray = array();
foreach ($array as $id => $dataset) {
$newArray[ $dataset['date_entered'] ] = $dataset;
}
我创建了一个新的数组因为这里的改变foreach循环中的数组可能会导致意外的行为的(的来源)。
如果你真的需要preserve你原来的数组,你可以使用数字索引来访问元素:
If you really need to preserve your original array, you can use your numeric indices for accessing the elements:
$arrCount = count($array);
for ($i=0; $i<$arrCount; $i++) {
$array[ $dataset['date_entered'] ] = $array[$i];
unset($array[$i]);
}
所有的元素被复制,他们得到取消设置前/在previous键删除。
All elements get copied before they get unset/deleted at the previous key.
这篇关于重命名多维数组相关联的钥匙的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!