Search a key array and return value

Asked

Viewed 2,757 times

1

I am manipulating a large XML file that when read returns several array, 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 research, for example, for "cash" it traverses all array and returns "50"

2 answers

5

You can take the keys of arrays with array_keys($array);

With this you can take the return and find the key you want. Then take the amount.

$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);
?>
  • Post an example @Marcondes, your answer will be much more complete

  • It does not "see" the multidimensional array, only returns the key of the first

  • Yes, so you have to make a recursion.... I’m seeing an example here...

  • I did a recursive update.

  • I know you already have a little time but would have to take only the first key of each array?

2


You can use the function array_walk_recursive, example:

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

IDEONE

  • What would it be like to return an array instead of strings? can have multiple results with the same key

  • @NGTHM4R3 vc can do so https://ideone.com/xklRSv

Browser other questions tagged

You are not signed in. Login or sign up in order to post.