Graham T
Graham T

Reputation: 966

Access array where key is a variable

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

This breaks. Is there anyway to do something like this?

I know you could explode $furtherKeys, count it, and setup a loop to achieve this, but I'm just curious if there is a direct way to concatenate an array with key names stored in a variable and have it work.

I want to use it for populating input field values from a json file. If I set a data-variable for each input field like:

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

I could get the value of the data-variable, then just slap it onto the json object, and populate the value.

Thanks!

Upvotes: 0

Views: 83

Answers (2)

Quixrick
Quixrick

Reputation: 3200

Although I don't know how to do this with both book and title at the same time, it is possible to use variables as key names using curly braces.

// 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};

This outputs:

The Parent Book Title Is: The Most Dangerous Game

Upvotes: 1

Andresch Serj
Andresch Serj

Reputation: 37388

You can simply parse your build up array access using eval(). See my 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;

Yet, i think it is better to use iteration. If $this->json['parent'] actually is an array, you write a recursive function to give you the result of the key.

See this ideone work 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');

Upvotes: 1

Related Questions