0

I have an array which contains the path to a specific value from an other array, to make it a bit more clear, here is an exemple.

My array containing the keys which I'll call $params

Array
(
    [0] => paths
    [1] => assets
    [2] => js
)

And here is my associative array which I'll call $config

Array
(
    [paths] => Array
        (
            [assets] => Array
                (
                    [js] => /assets/js
                    [css] => /assets/css
                )

        )

    [library] => Array
        (
            [js] => jQuery
        )

)

So how could I use my array 1 to access the value in my array 2?

I tried $config[$params[0]][$params[1]][$params[2]], but it's not efficient at all.

3 Answers 3

2

You can try

$path = array(
        0 => 'paths',
        1 => 'assets',
        2 => 'js',
);


$data = array(
  'paths' => array(
    'assets' => array(
      'js' => '/assets/js',
      'css' => '/assets/css',
    ),
  ),
  'library' => array(
    'js' => 'jQuery',
  ),
);


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

var_dump($temp);

Output

string '/assets/js' (length=10)
Sign up to request clarification or add additional context in comments.

1 Comment

Aren't you overwriting the $data array, every time you assign a value to the $temp reference (which points to $data)?
1

Hi Jonathan here you have missed one brace in the end try this "$config[$params[0]][$params[1]][$params[2]]". It will work I am posting a code which worked fine for me

<?php
$params = array(0 => 'paths',1 => 'assets',2 => 'js');
echo '<pre>';print_r($params);

$config = array
(
    'paths' => array
        (
            'assets' => array
                (
                    'js' => '/assets/js',
                    'css' => '/assets/css'
                )

        ),

    'library' => array
        (
            'js' => 'jQuery'
        )

);
echo '<pre>';print_r($config);
echo $config[$params[0]][$params[1]][$params[2]];
 ?>

Comments

1

A loop should solve your problem:

$c = $config;
foreach($params as $path) {
  if(!array_key_exists($path, $c)) {
    $c = null;
    break;
  }
  $c = $c[$path];
}

This will iterate over every entry in $params and then access the subkey of the $config array. After finding it, $c will contain the current subarray. In the end, $c will contain the value you were looking for (NULL if the path was invalid/not found).

The same can be done in a functional way using the array_reduce function:

$path = array_reduce(function($current, $path) {
  if($current == NULL || !array_key_exists($path, $current))
    return NULL;

  return $current[$path];
}, $params, $config);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.