Search for an array key and return value

1

I am manipulating a large XML file that when I read multiple array return, one inside the other, is it possible to search the key of an array and return its value? or an array if there is more than one key?

something like:

    array(
    'bio'=> array(
        'info'=> array(
               'cash'=>'50'
);
    );

And something to search, for example, for "cash" it runs through all the array and returns "50"     

asked by anonymous 30.06.2017 / 16:44

2 answers

2

You can use the array_walk_recursive function, for example:

$array = array('bio'=>array('info'=>array('cash'=>'50')));
function printFind($item, $key){
    if($key == 'cash'){
        echo $item;
    }
}
array_walk_recursive($array,'printFind');

IDEONE

    
30.06.2017 / 17:08
5

You can get Array keys with array_keys ($ array);

With this you can get the return and find the key you want. Then get the value.

$array = array("azul", "vermelho", "verde");
$key = array_keys($array, "vermelho"));
echo $array[$key];

Follow another example with recursion.

<?php
$array = array("color" => array("azul", "vermelho", "verde"),
               "size"  => array("joão", "maria", "pedro"));

function verificar(array $array)
{
    $keys = array();

    foreach ($array as $key => $value) {
        $keys[] = $key;

        if (is_array($value)) {
            $keys = array_merge($keys, verificar($value));
        }
    }

    return $keys;
}

$valores = verificar($array);
print_r($valores);
?>
    
30.06.2017 / 16:47