Skip to content

Instantly share code, notes, and snippets.

@ckhampus
Created April 3, 2014 05:56
Show Gist options
  • Save ckhampus/9948945 to your computer and use it in GitHub Desktop.
Save ckhampus/9948945 to your computer and use it in GitHub Desktop.
PHP Parent Array Iterator
<?php
$data = array(
array(
'id' => 1,
'children' => array(
array(
'id' => 12,
'children' => array(
)
),
array(
'id' => 13,
'children' => array(
array(
'id' => 131,
'children' => array(
array(
'id' => 1311,
'children' => array(
)
)
)
)
)
),
array(
'id' => 14,
'children' => array(
)
)
)
)
);
function search_in_array($needle, $haystack) {
$path = array();
$it = new RecursiveIteratorIterator(
new ParentIterator(new RecursiveArrayIterator($haystack)),
RecursiveIteratorIterator::SELF_FIRST
);
foreach ($it as $key => $value) {
if (array_key_exists('id', $value) && strcasecmp($value['id'], $needle) === 0) {
$path = $value;
break;
}
}
return $path;
}
var_dump(search_in_array(1311, $data));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment