Rocket
Rocket

Reputation: 57

PHP, How can i get the values from associative array by level

my question is how can i get all values from determined level of some array, i have this array:

array (size=4)
  'Azul' => 
    array (size=2)
      '128GB' => 
        array (size=2)
          'Cristal' => string 'Cristal' (length=7)
          'Plastico' => string 'Plastico' (length=8)
      '64GB' => 
        array (size=1)
          'Cristal' => string 'Cristal' (length=7)
  'Blanco' => 
    array (size=2)
      '32GB' => 
        array (size=1)
          'Plastico' => string 'Plastico' (length=8)
      '64GB' => 
        array (size=1)
          'Madera' => string 'Madera' (length=6)
  'Dorado' => 
    array (size=1)
      '64GB' => 
        array (size=1)
          'Plastico' => string 'Plastico' (length=8)
  'Verde' => 
    array (size=1)
      '64GB' => 
        array (size=1)
          'Madera' => string 'Madera' (length=6)

And i want get the first level with this recursive function, but i cant find more deeper than 2 levels for example i need the first level and i get:

Azul, Blanco, Dorado, Verde

But i need the second level of Azul i get: 128GB, 64GB

The questions is, if i need the 3rd level of Azul and 64GB, what can i do to get this, having the keys Azul and 64GB or level 3.

My recursive but buggy function is this:

function recursive($array, $level, $itemLVL)
    {
        foreach ($array as $key => $value) {
            //If $value is an array.
            if (is_array($value)) {
                //We need to loop through it.
                if ($level == $itemLVL) {
                    //echo "<br> Key: $key - Nivel:$level $itemLVL";
                    echo "<option value='$key'>$key</option>";
                }
                
                recursive($value, $level + 1, $itemLVL);
            } elseif ($level == $itemLVL) {
                echo "<option value='$key'>$key</option>";
            }
        }
    }

Upvotes: 1

Views: 66

Answers (1)

AbraCadaver
AbraCadaver

Reputation: 78994

If you know the key names and order, then something like this will return what is under those keys:

function get_array_path($path, $array) {
    $temp =& $array;

    foreach($path as $key) {
        $temp =& $temp[$key];
    }
    return $temp;
}

Pass an array of the keys in order:

$result = get_array_path(['Azul', '64GB'], $array);

If you just want the keys under the path and not everything else, then pass false as the third argument:

function get_array_path($path, $array, $values=true) {
    $temp =& $array;

    foreach($path as $key) {
        $temp =& $temp[$key];
    }
    if($values === false) {
        $temp = array_keys($temp);
    }
    return $temp;
}

Upvotes: 1

Related Questions