Author Topic: [SOLVED] "Pointers?" - reference in array to itself  (Read 129 times)

0 Members and 1 Guest are viewing this topic.

Offline phant0mTopic starter

  • Enthusiast
  • Gender: Male
    • View Profile
[SOLVED] "Pointers?" - reference in array to itself
« on: July 02, 2009, 09:20:50 AM »
Hello

I've got an array which basically represents a hierarchy of nodes. Each node can have children of its own.
Now, for easier access, I wanted to reference the parent node inside the child node, unfortunately it doesn't seem to work.

Simplified code:
Code: [Select]
<?php
foreach($parent['children'] as &$child){
  
$child['parent'] = &$parent;
}

?>
« Last Edit: July 02, 2009, 09:27:23 AM by phant0m »

Offline rhodesa

  • Guru
  • Freak!
  • *
  • Gender: Male
  • Bold and nosy. I'm famous for that.
    • View Profile
    • VectorLoft.com
Re: "Pointers?" - reference in array to itself
« Reply #1 on: July 02, 2009, 09:50:29 AM »
works for me:

Code: [Select]
<pre>
<?php
$parent 
= array(
  
'name' => 'I am the parent',
  
'children' => array(
    array(
      
'name' => 'I am the first child',
    ),
    array(
      
'name' => 'I am the second child',
    ),
    array(
      
'name' => 'I am the third child',
    ),
  ),
);

foreach(
$parent['children'] as &$child){
  
$child['parent'] = &$parent;
}

print 
$parent['children'][1]['parent']['name'];
print_r($parent);

?>
Aaron Rhodes
Lead Developer

Offline phant0mTopic starter

  • Enthusiast
  • Gender: Male
    • View Profile
Re: "Pointers?" - reference in array to itself
« Reply #2 on: July 02, 2009, 10:20:33 AM »
hmm yeah, it seems to work

anyway, I have solved my problem, accidentlly I referenced a reference and therefore changed some things unintentionally.

PHP Freaks Forums

« on: »

Tired of these ads? Purchase a supporter subscription to get rid of them.