Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sheershoff/f66354b63a77edbdc21c to your computer and use it in GitHub Desktop.
Save sheershoff/f66354b63a77edbdc21c to your computer and use it in GitHub Desktop.
php recursive search multidimensional array for value and return key sequences
<?php
namespace common\helpers;
class ArrayHelper extends \yii\helpers\ArrayHelper
{
public static function multiSearch($needle, $haystack, $options = ['strict' => false, 'yiiFormat' => false])
{
$iterator = new \RecursiveIteratorIterator(new \RecursiveArrayIterator([$haystack]));
// parent array is skipped in subiterators, so we wrap the argument in one more array
$results = [];
foreach ($iterator as $key => $value) {
if($options['strict']?($value === $needle):($value == $needle)) {
$keys = [];
for ($i = $iterator->getDepth()-1; $i > 0; $i--) {
$keys[] = $iterator->getSubIterator($i)->key();
}
$keys[] = $key;
$results[] = $keys;
}
}
if($options['yiiFormat']){
foreach($results as $k=>$v){
$results[$k] = implode('.',$v);
}
}
return $results;
}
}
@raph007
Copy link

raph007 commented Feb 26, 2017

You saved me some time. Thanks mate :)

@rosuciprian
Copy link

Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment