0

So far my var_dump() of a $records array looks like:

array (size=1)
  25 => 
    array (size=1)
      0 => 
        object(stdClass)[51]
          public 'id' => 25
          public 'name' => info...
          public 'surname' => info...

I wan't to change that 0 index name to object id (25) name but it just adds one more dimension above my current one. This is how I do it:

foreach ($records as $value) {
    $records = array($value->id=>$records);
}

I want my array to look like this though:

array (size=1)
  25 => 
    object(stdClass)[51]
     public 'id' => 25
     public 'name' => info...
     public 'surname' => info...

1 Answer 1

1

Updating keys so they equal the ID:

$tmp= array();
foreach ($records as $value) {
    $tmp[$value->id] = $value;
}
$records = $tmp;
Sign up to request clarification or add additional context in comments.

7 Comments

hmm maybe I wasn't clear enough or I don't understand. I want to rename the original index of my array $records[0] to $records[$value->id] and do it in my loop so in case I have more indexes all of them get renamed after their id
I've updated my code. Basically you build a new array and just set the key using the method I've shown.
I see it works, however I now have a new array variable called $results... Any chance I can keep the same old name? A lot of code is depending on it
Yeah, you want to overwrite the old name with the name new $origName = $newName. You must use a temporary name because you cannot loop through and modify the original array at the same time.
I see, can I rename it in the loop?
|

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.