0

I have an array of std objects.

I wish to rename them.

How do I do it?

Eg

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

How to rename the values 0, 1, 2 to something else?

--- Updated below ---

I'm using this now

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

But at the expense of an additional array dimension.

Was trying to change something like this

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

to...

Array(
    [10] stdClass
        tid => 10
        name => Category
    [11] stdClass
        tid => 11
        name => Product
)
2
  • Can you rephrase your question? Do you want to change the keys to something else? Can you show an actual var_dump of a real array and an example of what you would like to change it to? Commented Jan 5, 2011 at 3:11
  • indeed i meant the keys. Commented Jan 5, 2011 at 7:01

2 Answers 2

2
$new_arr = array();
foreach ($array as $val)
{
  $new_arr[(int)$val->tid] = $val;
}
Sign up to request clarification or add additional context in comments.

2 Comments

Hmm, what has this got to do with it, he remapping his array index thats all, nothing to do with casting.
that's before the second upate
1

Something like this maybe

$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;
}

This will loop every element in your array and check it against the mappings array, if the key exists it will add the value to the correct index and remove the old integer based index.

Also this should be ok with scope and references,

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.