Array containing keys and associative array, how to make a relation

自闭症网瘾萝莉.ら 提交于 2020-01-06 08:17:18

问题


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.


回答1:


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)



回答2:


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);



回答3:


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]];
 ?>


来源:https://stackoverflow.com/questions/14039318/array-containing-keys-and-associative-array-how-to-make-a-relation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!