K
K
kpa6uu2016-07-13 23:38:57
PHP
kpa6uu, 2016-07-13 23:38:57

How to "walk" through the keys of an array?

Hello.
Straight to the point - an example.
We have an array like this:

$array = array(
  'one' => 'hi',
  'two' => 'privet',
  'three' => array('three_1' => 'hi', 'three_2' => 'privet'),
);

I have the following line:
$str = 'three|three_1';
How to address an array cell on the given line?
Tried as follows, didn't work:
$exp = explode('|', $str);
$key = '["'.implode('"]["', $exp).'"]'; //["three"]["three_1"]
var_dump($array[$key]); //null

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Vapelnik, 2016-07-13
@kpa6uu

for this narrow example something like this:

$array = array(
  'one' => 'hi',
  'two' => 'privet',
  'three' => array('three_1' => 'hi', 'three_2' => 'privet'),
);

$str = 'three|three_1';

$keys = explode("|", $str);

var_dump($array[$keys[0]][$keys[1]]);

<?php

function foo($array, $str){
  $keys = explode('|', $str);
  
  $keysCount = count($keys);
  
  $result = $array;
  for($i = 0; $i < $keysCount; $i++){
    if(!is_array($result) && $i < ($keysCount - 1)){
      throw new Exception("Array depth not expected");
    }
    
    if(!isset($result[$keys[$i]])){
      throw new Exception(sprintf("Key '%s' not found", $keys[$i]));
    }
    
    $result = $result[$keys[$i]];
  }
  
  return $result;
}

$array = array(
  'one' => 'hi',
  'two' => 'privet',
  'three' => array('three_1' => 'hi', 'three_2' => 'privet'),
);

$str = 'three|three_1';

var_dump(foo($array, $str));

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question