We have an array with many objects in a style like
<?php
$step = new StepModel(1); // if the StepModel id is "1"
$demand = $step->getDemand(); // returns DemandModel
$step2 = $demand->getCustomer(); // returns StepModel
$demand2 = $step2->getDemand(); // returns DemandModel
// [ ... ]
?>
$step and $step2 can be the same objects. So we have an recursive array. Now we need to know if $step == $step2 or $step === $step2. In other words: We need to know the php internal resource ids.
Because there is no function in php api, we made the following function.
Be careful: In our case, all objects have as first attribute ["id":protected]. If your objects are different from this, you need to edit $pattern.
Warning: function is very slow and should only be called if it's necessary for debugging reasons:
<?php
/**
* returns resource- and object-ids of all objects in an array
*
* @param array $array
* @return array
*/
function getObjectInformation(Array $array)
{
// start output-buffering
ob_start();
// create an var_dump of $array
var_dump($array);
// save the dump in var $dump
$dump = ob_get_contents();
// clean the output-buffer
ob_end_clean();
// delete white-spaces
$dump = str_replace(' ', '', $dump);
// define the regex-pattern
// in our case, all objects look like this:
//
// object(ClassName)#1(1){
// ["id":protected]=>
// string(1)"1"
$pattern = '/object\(([a-zA-Z0-9]+)\)#([0-9]+)\([0-9]+\){\\n';
$pattern .= '\["id":protected\]=>\\n';
$pattern .= 'string\([0-9]+\)"([v]?[0-9]+)"/im';
// search for all matches
preg_match_all($pattern, $dump, $regs);
// sort all mathes by class name, object id and then resource id
array_multisort($regs[1], SORT_ASC, SORT_STRING,
$regs[3], SORT_ASC, SORT_NUMERIC,
$regs[2], SORT_ASC, SORT_NUMERIC);
// cache the last match
$lastMatch = array();
// the return value
$return = array();
// loop through the matches
for ($i = 0; $i < sizeof($regs[0]); $i ++) {
// check if the current match was not visited before
if (0 == sizeof($lastMatch) ||
$regs[1][$i] != $lastMatch[1] ||
$regs[2][$i] != $lastMatch[2] ||
$regs[3][$i] != $lastMatch[3]) {
// save the match in return value
array_push($return, array($regs[1][$i],
$regs[2][$i],
$regs[3][$i]));
}
// save match in last match cache
$lastMatch[1] = $regs[1][$i];
$lastMatch[2] = $regs[2][$i];
$lastMatch[3] = $regs[3][$i];
}
// return all matches
return $return;
}
?>
I know, it's not that elegant but I hope it's useful for a few people.