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...
Steve Tauber
  • 9,551
  • 5
  • 42
  • 46
LazyPeon
  • 339
  • 1
  • 19

1 Answers1

1

Updating keys so they equal the ID:

$tmp= array();
foreach ($records as $value) {
    $tmp[$value->id] = $value;
}
$records = $tmp;
Steve Tauber
  • 9,551
  • 5
  • 42
  • 46
  • 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 – LazyPeon Aug 08 '14 at 10:27
  • I've updated my code. Basically you build a new array and just set the key using the method I've shown. – Steve Tauber Aug 08 '14 at 10:28
  • 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 – LazyPeon Aug 08 '14 at 10:30
  • 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. – Steve Tauber Aug 08 '14 at 10:32
  • I see, can I rename it in the loop? – LazyPeon Aug 08 '14 at 10:35
  • You have to do the loop first then rename it afterwards. I'll update my code – Steve Tauber Aug 08 '14 at 10:39
  • You don't want to overwrite the array until after the loop because otherwise you are modifying the data as you are looping through it. This question is pretty good: http://stackoverflow.com/questions/10057671/how-foreach-actually-works – Steve Tauber Aug 08 '14 at 10:42