Home > Net >  how to get the last array with a specific key in multidimensional array
how to get the last array with a specific key in multidimensional array

Time:10-27

I am looking for a function to return an array and all its sub-structure for a specific criteria

Criteria:

  • php 5.6 compatible
  • Return the last instance of array with key name of !ENTITY with all its values in-tact

Sample array:

For the multidimensional array, lets call that $arr, for this example structure it's 6 levels deep, we should not assume it's always 6 levels.

$arr = array("!ENTITY" =>
             array("!ENTITY" =>
                array("!ENTITY" =>
                    array("!ENTITY" =>
                        array("!ENTITY" =>
                            array("!ENTITY" =>
                                array("svg" => 
                                     array(
                                         0 => array("g" => "", "@id" => "Layer_2"),
                                         1 => array("g" => "", "@id" => "Layer_3"),
                                     ),
                                     "@version" => 1.2,
                                     "@id" => "Layer_1",
                                ),
                            "@different" => "layer"
                            ),
                        "@all" => "layer"
                        ),
                    "@here" => "layer"
                    ),
                "@goes" => "layer"
                ),
            "@else" => "layer"
            ),
   "@something" => "layer"
   );

Expected Output:

I would like to return the final array for !ENTITY with it's sub-structure all in-tact. Here is a sample of the expected output:

Array
    (
        [svg] => Array
            (
                [0] => Array
                    (
                        [g] => 
                        [@id] => Layer_2
                    )

                [1] => Array
                    (
                        [g]
                        [@id] => Layer_3
                    )

            )

        [@version] => 1.2
        [@id] => Layer_1
    )

CodePudding user response:

You will need to recursively traverse the array and return resultant values if found like below:

<?php

function getLastValueForKey($data, $key){
    $res = '';
    foreach($data as $k => $value){
        $sub_res = is_array($value) ? getLastValueForKey($value, $key) : '';
        if($sub_res !== ''){
            $res = $sub_res;
        }else if($k === $key){
          $res = $value;
        }
    }
    return $res;
}
   
print_r(getLastValueForKey($arr, '!ENTITY'));

Online Demo

  • Related