php - Optimise search in JSON with strings in ascending order -
i have json here
at root, there command(property) wp has 39 sub-commands(sub-properties) cache, cap, checksum...etc, each has own subcommands , goes 4 levels
the better part subcommands arranged in ascending order, i.e.; strings arranged in ascending order.
i want traverse , search whether command wp site create or wp term delete exists in json tree. don't want iterate using for loop due huge time complexity. it's been long since i've completed engineering , if memory serves correctly, tree structure improvise search time.
can point me right direction on achieving this? i'm using php language.
here's binary search solution, you'll need put json file...
note: because wp isn't in subcommands array can't search it
<?php function binarysearch(&$myarray, $search, $start, $end) { $middle = ($start + $end) >> 1; // divide 2 if ($middle >= $start) { if ($search > $myarray[$middle]['name']) { // $search must in top half of array $result = binarysearch($myarray, $search, $middle + 1, $end); } elseif ($search < $myarray[$middle]['name']) { // $search must in bottom half of array $result = binarysearch($myarray, $search, $start, $middle - 1); } else { // $search here $result = $middle; } } else { $result = false; // $search not found } return $result; } function findcommand($arrfound, $strfind) { $arrfind = explode(' ', $strfind); while ($arrfound !== false , list($key, $strcommand) = each($arrfind)) { $arrsearch = $arrfound['subcommands']; if (($key = binarysearch($arrsearch, $strcommand, 0, count($arrsearch) - 1)) === false) { $arrfound = false; } else { $arrfound = $arrsearch[$key]; } } return $arrfound; } // json file , convert array $arrjson = json_decode(file_get_contents('items.json'), true); $arrcommand = findcommand($arrjson, 'site create'); var_dump($arrcommand); $arrcommand = findcommand($arrjson, 'term delete'); var_dump($arrcommand);
Comments
Post a Comment