Hiranya Hiranya - 3 months ago 8
PHP Question

Find parent keys in hierarchy in PHP

I have below

Array
structure for
$array
.

Array
(
[WIDGET_BUILDER_CREATE] => Array
(
[TITLE] => Widget Builder
[WIDGET_TYPE_LBL] => Select Widget Type
[RANGE_LBL] => Select Range
[RANGE_TYPE_LBL] => Select Range Type
[TOP_SERVICE_CHKBOX] => Top Services
[SR_STATE_LBL] => Select Sr States
[SR_TYPE_LBL] => Select Sr Types
[SR_CATEGORY_LBL] => Select Sr Categories
[SR_SOURCE_LBL] => Select Sources
[SR_PROVIDER_LBL] => Select Sr Provider
[ADDRESS] => Enter Address
[SUBMIT_BTN] => Generate Data
[CHART_DIV] => Array
(
[TYPE] => Select chart type
[SAVE_BTN] => Save Widget
[SERIES_NAME] => Change Parameters
[PARA_DIALOG] => Array
(
[TITLE] => Chart Parameters
[SERIESNAME] => Series Name
[YAXISNAME] => Y axies name
[VALIDATION] => Array
(
[SERIESNAME] => Please enter series name
[YAXISNAME] => Please enter y axis name
)

[SAVE_BTN] => Save
[CANCEL_BTN] => Cancel
)

[SAVE_DIALOG] => Array
(
[TITLE] => Save Chart
[CHART_NAME] => Chart Name
[SHOW_TO_USER] => System Widget
[VALIDATION] => Array
(
[CHART_NAME] => Please enter chart name
)

[SAVE_BTN] => Save
[CANCEL_BTN] => Cancel
)

)

[GRID_DIV] => Array
(
)

)

)


Problem:

I want to build a
function
in
PHP
like if I enter a
value
,then it should return all
parent keys
in hierarchy.

Let's say for example if I enter
Please enter y axis name
,it should return as

$array['WIDGET_BUILDER_CREATE']['CHART_DIV']['PARA_DIALOG']['VALIDATION']['YAXISNAME'];


Edit: I tried like How to get hierarchy path of an element in an Array but it returns as a string but I want as
array key indexed
. That means

print_r($array['WIDGET_BUILDER_CREATE']['CHART_DIV']['PARA_DIALOG']['VALIDATION']['YAXISNAME']);

//returns Please enter y axis name


I am using
PHP 5.5.9

Answer

If you are feeling like you could use a quick & dirty approach, you may want to try the function below which uses nested foreach Loops. But then, if you are feeling geeky, you could simply refactor the nested loops on your own and turn them into a shorter recursive algorithm. To test this Quick & Dirty method, go here:

SAMPLE DATA:

<?php

    $array = [
        'WIDGET_BUILDER_CREATE' => [
            "TITLE"                 => "Widget Builder",
            "WIDGET_TYPE_LBL"       => "Select Widget Type",
            "RANGE_LBL"             => "Select Range",
            "RANGE_TYPE_LBL"        => "Select Range Type",
            "TOP_SERVICE_CHKBOX"    => "Top Services",
            "SR_STATE_LBL"          => "Select Sr States",
            "SR_TYPE_LBL"           => "Select Sr Types",
            "SR_CATEGORY_LBL"       => "Select Sr Categories",
            "SR_SOURCE_LBL"         => "Select Sources",
            "SR_PROVIDER_LBL"       => "Select Sr Provider",
            "ADDRESS"               => "Enter Address",
            "SUBMIT_BTN"            => "Generate Data",
            "CHART_DIV"             => [
                "TYPE"          => "Select chart type",
                "SAVE_BTN"      => "Save Widget",
                "SERIES_NAME"   => "Change Parameters",
                "PARA_DIALOG"   => [
                    "TITLE"         => "Chart Parameters",
                    "SERIESNAME"    => "Series Name",
                    "YAXISNAME"     => "Y axies name",
                    "VALIDATION"    => [
                        "SERIESNAME"    => "Please enter series name",
                        "YAXISNAME"     => "Please enter y axis name",

                    ],
                    "SAVE_BTN"          => "Save",
                    "CANCEL_BTN"        => "Cancel",
                ],
                "SAVE_DIALOG"   =>[
                    "TITLE"         => "Save Chart",
                    "CHART_NAME"    => "Chart Name",
                    "SHOW_TO_USER"  => "System Widget",
                    "VALIDATION"    => [
                        "CHART_NAME"    => "Please enter chart name",
                    ],
                    "SAVE_BTN"      => "Save",
                    "CANCEL_BTN"    => "Cancel",
                ],

            ],
            "GRID_DIV"              => [],
        ],
    ];

QUICK & DIRTY FUNCTION:

<?php

    function keywordLookUp(array $array, $keyWord, $arrayName="\$array"){
        $route   = $mainKey   = null; $arrRte   = $arrResult   = [];
        foreach($array as $intKey=>$item){
            $mainKey =  $route = "{$arrayName}['{$intKey}']";
            if(is_array($item)){
                foreach($item as $iKey=>$innerItem){
                    if($lKey = array_search($keyWord, $item)){
                        $route .=  $s = "['$lKey']"; break;
                    }
                    if(is_array($innerItem)){
                        foreach($innerItem as $iKey2=>$innerItem2){
                            if($lKey = array_search($keyWord, $innerItem)){
                                if(isset($s)){
                                if(! array_search($route, $arrRte)){$arrRte[] = $route;}
                                    $arrRte[] =  "{$s}['$lKey']";
                                    $route .=  "\n{$s}['$lKey']";
                                }else{
                                    $route .=  "['$iKey']['$lKey']";
                                }   $s      =  str_replace("['$lKey']", "", $route); break;
                            }
                            if(is_array($innerItem2)){
                                foreach($innerItem2 as $iKey3=>$innerItem3){
                                    if($lKey = array_search($keyWord, $innerItem2)){
                                        if(isset($s)){
                                            if(! array_search($route, $arrRte)){$arrRte[] = $route;}
                                            $arrRte[] ="{$s}['$iKey2']['$lKey']";
                                            $route .=  "\n{$s}['$iKey2']['$lKey']";
                                        }else{
                                            $route .=  "['$iKey']['$iKey2']['$lKey']";
                                        }   $s      =  str_replace("['$iKey2']['$lKey']", "", $route); break;
                                    }
                                    if(is_array($innerItem3)){
                                        foreach($innerItem3 as $iKey4=>$innerItem4){
                                            if($lKey = array_search($keyWord, $innerItem3)){
                                                if(isset($s)){
                                                    if(! array_search($route, $arrRte)){$arrRte[] = $route;}
                                                    $arrRte[] = "{$s}['$iKey3']['$lKey']";
                                                    $route .=  "\n{$s}['$iKey3']['$lKey']";
                                                }else{
                                                    $route .=  "['$iKey']['$iKey2']['$iKey3']['$lKey']";
                                                }break;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        $fin = ($route == $mainKey) ? null : $route;
        $fin = (!empty($arrRte) && sizeof($arrRte > 1))?$arrRte:$fin;
        return $fin;
    }

    $path  = keywordLookUp($array, "Please enter y axis name");
    $path2 = keywordLookUp($array, "Chart Parameters");
    $path3 = keywordLookUp($array, "Cancel");

    var_dump($path);
    // PRODUCES::  string '$array['WIDGET_BUILDER_CREATE']['CHART_DIV']['PARA_DIALOG']['VALIDATION']['SERIESNAME']' (length=87)

    var_dump($path2);
    // PRODUCES::  string '$array['WIDGET_BUILDER_CREATE']['CHART_DIV']['PARA_DIALOG']['TITLE']' (length=68)

    var_dump($path3);
    // PRODUCES:: 
    array (size=2)
      0 => string '$array['WIDGET_BUILDER_CREATE']['CHART_DIV']['PARA_DIALOG']['CANCEL_BTN']' (length=73)
      1 => string '$array['WIDGET_BUILDER_CREATE']['CHART_DIV']['SAVE_DIALOG']['CANCEL_BTN']' (length=73)