修改数组键

时间:2011-01-05 03:09:33

标签: php arrays

我有一组std对象。

我希望重命名它们。

我该怎么做?

例如

Array(  
    [0] stdClass  
        key => values  
    [1] stdClass  
        key => values  
    [2] stdClass  
        key => values  
)

如何将值0,1,2重命名为其他内容?

--- 在下面更新 ---

我现在正在使用

foreach ($arr as $value) {
    $new_arr[] = array('my_key' => $value);
}

但是以额外的数组维度为代价。

试图改变这样的事情

Array(
    [0] stdClass
        tid => 10
        name => Category
    [1] stdClass
        tid => 11
        name => Product
)

为...

Array(
    [10] stdClass
        tid => 10
        name => Category
    [11] stdClass
        tid => 11
        name => Product
)

2 个答案:

答案 0 :(得分:2)

$new_arr = array();
foreach ($array as $val)
{
  $new_arr[(int)$val->tid] = $val;
}

答案 1 :(得分:1)

这样的事可能

$mapping = array(
     0 => "object_0",
     1 => "object_1",
     2 => "object_2",
     3 => "object_3",
);

foreach($my_array as $key => $value)
{
     //Check to see if there's a key, else use integer
     $_key = isset($mapping[$key]) ? $mapping[$key] : $key;

     //Remove the old one | 0,1,2 ... $value already in scope, and not referenced.
     unset($my_array[$key]);

     //And key 0 to index object_0 etc
     $my_array[$_key] = $value;
}

这会遍历数组中的每个元素并针对映射数组进行检查,如果键存在,它会将值添加到正确的索引并删除旧的基于整数的索引。

这也应该适用于范围和参考,