Last active
August 5, 2019 10:49
-
-
Save sheershoff/f66354b63a77edbdc21c to your computer and use it in GitHub Desktop.
php recursive search multidimensional array for value and return key sequences
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You saved me some time. Thanks mate :)