0
$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!

2 Answers 2

1

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');
Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

Yeah, you can do this with square brackets also. $json['parent'][$key1]. I was playing with this format and looping, which is totally fine. I was just wondering if there was some quick and dirty way to concatenate the two together. Thanks for the reply!

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.