访问数组,其中键是变量

时间:2014-04-07 15:08:03

标签: php arrays json

$furtherKeys = "['book']['title']";
echo $this->json['parent'] . $furtherKeys;

这打破了。无论如何都要做这样的事情吗?

我知道你可以爆炸$ FurtherKeys,计算它,并设置一个循环来实现这一点,但我只是好奇是否有一种直接的方法来连接一个数组与存储在变量中的键名并让它工作。

我想用它来填充json文件中的输入字段值。如果我为每个输入字段设置数据变量,如:

<input type="text" data-keys="['book']['title']">

我可以获取数据变量的值,然后将其打到json对象上,然后填充该值。

谢谢!

2 个答案:

答案 0 :(得分:1)

您可以使用eval()简单地解析构建阵列访问。请参阅我的exaple here

$example = array(
    'foo' => array(
        'hello' => array(
            'world' => '!',
            'earth' => '?'
            )
        ),
    'bar' => array());
// your code goes here

$yourVar = null;
$access  = "['foo']['hello']['world']";

$actualAccesEvalCode = '$yourVar = $example'.$access.';';

eval($actualAccesEvalCode);

echo 'YourVal now is '.$yourVar;

然而,我认为使用迭代更好。如果$this->json['parent']实际上是一个数组,则编写一个递归函数来为您提供密钥的结果。

请参阅此ideone作品here

<?php

$example = array(
    'foo' => array(
        'hello' => array(
            'world' => '!',
            'earth' => '?'
            )
        ),
    'bar' => array());

    function getArrayValueByKeyString($array,$keystring) {
      $dotPosition = stripos ($keystring , '.' );
      if($dotPosition !== FALSE) {
        $currentKeyPart   = substr($keystring, 0, $dotPosition);
        $remainingKeyPart = substr($keystring, $dotPosition+1);

        if(array_key_exists($currentKeyPart, $array)) {
          return getArrayValueByKeyString(
            $array[$currentKeyPart],
            $remainingKeyPart);
        }
        else {
          // Handle Error
        }
      }
      elseif (array_key_exists($keystring, $array)) {
        return $array[$keystring];
      }
      else {
        // handle error
      }
    }

    echo '<hr/>Value found: ' . getArrayValueByKeyString($example,'foo.hello.world');

答案 1 :(得分:1)

虽然我不知道如何同时使用booktitle,但可以使用大括号将变量用作键名。

// SET UP AN ARRAY
$json = array('parent' => array('book' => array('title' => 'The Most Dangerous Game')));

// DEFINE FURTHER KEYS
$furtherKeys1 = "book";
$furtherKeys2 = "title";

// USE CURLY BRACES TO INSERT VARIABLES AS KEY NAMES INTO YOUR PRINT STATEMENT
print "The Parent Book Title Is: ".$json['parent']{$furtherKeys1}{$furtherKeys2};

输出:

The Parent Book Title Is: The Most Dangerous Game
相关问题