$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!
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');
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
Related
I'm trying to execute variable which part of it is a string.
Here it is:
$row = array(
'index_1' => array(
'index_2' => 'my-value'
)
);
$pattern = "['index_1']['index_2']";
I tried to do it in following ways:
// #1
$myValue = $row{$pattern};
// #2
$myValue = eval("$row$pattern");
I also trying to get it working with variable variable, but not successful.
Any tips, how should I did it? Or myabe there is other way. I don't know how may look array, but I have only name of key indexes (provided by user), this is: index_1, index_2
You could use eval but that would be quite risky since you say the values come from user input. In that case, the best way might be to parse the string and extract the keys. Something like this should work:
$pattern = "['index_1']['index_2']";
preg_match('/\[\'(.*)\'\]\[\'(.*)\'\]/', $pattern, $matches);
if (count($matches) === 3) {
$v = $row[$matches[1]][$matches[2]];
var_dump($v);
} else {
echo 'Not found';
}
This can help -
$row = array(
'index_1' => array(
'index_2' => 'my-value'
)
);
$pattern = "['index_1']['index_2']";
$pattern = explode("']['", $pattern); // extract the keys
foreach($pattern as $key) {
$key = str_replace(array("['", "']"), '', $key); // remove []s
if (isset($row[$key])) { // check if exists
$row = $row[$key]; // store the value
}
}
var_dump($row);
Storing the $row in temporary variable required if used further.
Output
string(8) "my-value"
If you always receive two indexes then the solution is quite straight forward,
$index_1 = 'index_1';// set user input for index 1 here
$index_2 = 'index_2';// set user input for index 2 here
if (isset($row[$index_1][$index_2])) {
$myValue = $row[$index_1][$index_2];
} else {
// you can handle indexes that don't exist here....
}
If the submitted indexes aren't always a pair then it will be possible but I will need to update my answer.
As eval is not safe, only when you know what you are ding.
$myValue = eval("$row$pattern"); will assign the value you want to $myValue, you can add use return to make eval return the value you want.
here is the code that use eval, use it in caution.
demo here.
<?php
$row = array(
'index_1' => array(
'index_2' => 'my-value'
)
);
$pattern = 'return $row[\'index_1\'][\'index_2\'];';
$myValue = eval($pattern);
echo $myValue;
I want to store square bracket string in a variable so that I can use that variable to get the value of array. How can I do that?
Example:
$vehicle = array("car"=>"volvo","bike"=>"polygon");
$bracket1="['car']";
$bracket2="['bike']";
echo $vehicle.$bracket1;//my expected result = 'volvo';
echo $vehicle.$bracket2;//my expected result = 'polygon';
Case
Suppose I have this data
$data = array(
"vehicles"=>array(
array(
"name"=>"volvo",
"manufacturer"=>"abc",
"color"=>array("blue"=>"wonderful","red"=>"fantastic")),
array(
"name"=>"toyota",
"manufacturer"=>"def",
"color"=>array("blue"=>"awesome","red"=>"good")),
array(
"name"=>"mecedes",
"manufacturer"=>"ghi",
"color"=>array("blue"=>"nice","red"=>"great","green"=>"good","brown"=>"elegant")),
));
$fields = array(
"$data['vehicles']['name']",
"$data['vehicles']['manufacturer']",
"$data['vehicles']['color']['blue']",
"$data['vehicles']['color']['red']"
);
//a function to print those data according to user parameter($fields, it may uncertain pattern)
function get_data($data,$fields){
for($c=0;$c<count($data);$c++){
foreach($fields as $field){ //field to show
echo $field;
}
}
}
edited:
$data = array(
"vehicles"=>array(
array(
"name"=>"volvo",
"manufacturer"=>"abc",
"color"=>array("blue"=>"wonderful","red"=>"fantastic")),
array(
"name"=>"toyota",
"manufacturer"=>"def",
"color"=>array("blue"=>"awesome","red"=>"good")),
array(
"name"=>"mecedes",
"manufacturer"=>"ghi",
"color"=>array("blue"=>"nice","red"=>"great","green"=>"good","brown"=>"elegant")),
));
$c=0;
$fields = array( // note added zeros here... these are your "vehicle" array key
"{$data['vehicles'][$c]['name']}",
"{$data['vehicles'][$c]['manufacturer']}",
"{$data['vehicles'][$c]['color']['blue']}",
"{$data['vehicles'][$c]['color']['red']}"
);
for($c=0;$c<count($data['vehicles']);$c++){
foreach($fields as $field) {
echo $field . PHP_EOL;
}
}
//the output print : volvo abc wonderful fantastic volvo abc wonderful fantastic volvo abc wonderful fantastic
//the output expectetd : volvo abc wonderful fantastic toyota dev awesome good mercedes ghi nice great
Why don't you try this:
$vehicle = array("car" => "volvo", "bike" => "polygon");
$bracket1 = "car";
$bracket2 = "bike";
echo $vehicle[$bracket1]; //my expected result = 'volvo';
echo $vehicle[$bracket2]; //my expected result = 'polygon';
Edit: you want a function that does this... You don't need it. This is a basic PHP language construct.
Anywho, here's your function (wrapping that basic PHP language construct up in an extra layer) - I'll even throw in a basic error check (return false if the array key doesn't exist):
function searchMyHugeArrayForSomething($huge_array, $something) {
if(!array_key_exists($something, $huge_array))
return false; // return false if array key doesn't exist
return $huge_array[$something]; // return your desired result......
}
Demo:
$my_huge_array = array(
'pet' => 'cat',
'wife' => 'sarah',
'brother' => 'john'
// etc
);
echo searchMyHugeArrayForSomething($my_huge_array, 'wife'); // sarah
echo searchMyHugeArrayForSomething($my_huge_array, 'husband'); // returns false (oop, sexist!)
echo searchMyHugeArrayForSomething($my_huge_array, 'brother'); // john
// etc............?
Make sense?
Edit: OK, multidimensional array is very different (your original question was flat). You are having an issue here because you're missing a level in between vehicles and name, etc. There's an array there containing numeric indexes, so your path would actually be $data['vehicles'][0]['name'] - and when that's the case, you can basically just echo each line of your array to get the value of the array key parsed into a string.
In this example I've added both curly braces to each line to parse as a variable variable, and because your example won't actually run as it is (it's trying to parse the array keys as a variable and syntactically failing), and added the zero array key. You'll need to work out which array key you want to target yourself, this is just using the first:
$fields = array( // note added zeros here... these are your "vehicle" array key
"{$data['vehicles'][0]['name']}",
"{$data['vehicles'][0]['manufacturer']}",
"{$data['vehicles'][0]['color']['blue']}",
"{$data['vehicles'][0]['color']['red']}"
);
foreach($fields as $field) {
echo $field . PHP_EOL;
}
Output:
volvo
abc
wonderful
fantastic
I'm showing a "Review Your Order:" part of a page with the success callback of a json_encode array. I probably said that completely wrong in technical terms but hopefully you can see what I'm trying to do.
Part of the PHP processing page...
$results = array(
'roomname' => $_POST['roomX'],
'qty' => $_POST['qtyX'],
and I want the results to be returned as...
Room Name: Whatever is returned. (notice the label "Room Name: ")
But I only want the label to show IF the POST has a value assigned.
Example of how I think it should look but it's not working..
$results = array(
'roomname' => if (!$_POST['roomX']=='' { echo 'Room Name: ' .$_POST['roomX'];},
Does that make sense? There are dozens of options for each order and I don't want "Label: " in front of a bunch of values that are empty.
EDIT: Added code from answer below.
// beginning of array
$results = array(
'roomname' => $_POST['roomX'],
'qty' => $_POST['qtyX'],
// more code...
// end of array.. remember not to have a comma on this last one.
);
// pasted answer between the array ending and the json_encode line.
if ($_POST['roomX'] != ''){
$results['roomname'] = "Room Name: ".$_POST['roomX'];
}
$json = json_encode($results);
echo $json;
here is one way, you can user a Ternary operation
$results = array(
'roomname' => $_POST['roomX']==''? 'Room Name: '.$_POST['roomX']: '',
);
this will add a blank string if the value is empty
the other way will be to just add the value later;
$results = array(...);
if ($_POST['roomX'] != ''){
$results['roomname'] = $_POST['roomX']
}
$results = array();
if (isset($_POST['roomX'])) {
$results[] = array(...);
}
if there's no post value, you just end up with an empty array.
you can make an if statement before assigning any data to roomname like so
$result = array(
'roomname' => ($_POST['roomX'] !== '')? 'Room name: '.$_POST['roomX']:''
);
The thing I used here is a shortend if statement and works as following: (if statement)? true : false;
I hope this will help you.
I what to get a value returned from a object method and put it into an array. The codes is as follows:
$additionalTestConfirmation = array();
$additionalTests = $this->getAdditionalTestsSelected();
foreach($additionalTests as $availableTest)
{
$additionalTestConfirmation = $availableTest->getName();
}
$appointment = $this->getAppointment();
$tokens = array(
'%DATE%' => $this->getAppointment()->getDate(),
'%LOCATION%' => $this->getAppointment()->getLocation(),
'%TIME%' => $this->getTime(),
'%ROOM%' => $this->getRoom(),
'%NAME%' => ($this->getUser() ? $this->getUser()->getFullName() : null),
'%TZ%' => $this->getAppointment()->getShowTimeZone() ? $this->getAppointment()->getTimeZone() : '',
'%AdditionalTestsSelected%' => $additionalTestConfirmation,
);
For the codes above, I got a system error message: Notice: Array to string conversion in /Users/alexhu/NetBeansProjects/menagerie/svn/trunk/apps/frontend/modules/legacy/legacy_lib/lib/classes/AppointmentTime.php on line 379.
How do I avoid this and get the $availableTest->getName() returned value I want. thanks
When you assign elements to an array, you must either specify an index, or use empty square brackets ([]) to add an item:
foreach($additionalTests as $availableTest) {
$additionalTestConfirmation[] = $availableTest->getName();
// or array_push($additionalTestConfirmation, $availableTest->getName());
// see: http://us3.php.net/array_push
}
See the docs for more: http://php.net/manual/en/language.types.array.php
EDIT
Also, on this line:
'%AdditionalTestsSelected%' => $additionalTestConfirmation,
... you are passing an array into this index. If the code afterword expects this to be a string, that could cause the errors. *This is not causing the error - it is perfectly acceptable to put an array in another array. As I mentioned, though, it really depends on what the code that uses the $tokens array will do and expect. If it expects a plain string for the AdditionalTestsSelected index, you might need to do this:
'%AdditionalTestsSelected%' => implode(',', $additionalTestConfirmation)
... to make the value a comma-delimited list.
Also note, at the end of that line you have an extra comma.
In order to add each $availableTest->getName() to the array $additionalTestConfirmation you need to use [] on your array and the assignment operator =
foreach($additionalTests as $availableTest)
{
$additionalTestConfirmation[] = $availableTest->getName();
}
You can also use the function array_push
foreach($additionalTests as $availableTest)
{
$additionalTestConfirmation[] = $availableTest->getName();
}
after your comment I propose you this:
$appointment = $this->getAppointment();
$token = array(
'%DATE%' => $appointment->getDate(),
'%LOCATION%' => $appointment->getLocation(),
'%TIME%' => $this->getTime(),
'%ROOM%' => $this->getRoom(),
'%NAME%' => ($this->getUser() ? $this->getUser()->getFullName() : null),
'%TZ%' => $appointment->getShowTimeZone() ? $appointment->getTimeZone() : ''
);
$tokens = array();
$additionalTests = $this->getAdditionalTestsSelected();
foreach($additionalTests as $availableTest)
{
$token['%AdditionalTestsSelected%'] = $availableTest->getName();
$tokens[] = $token;
}
// here comes logic for all tokens
Thanks for the help below, however, I'm still having some problems, I'll try and explain further:
I have a variable as follows:
$value['questions'];
Now, I need to do a check in a loop, so I have this piece of code in the loop:
if($results[$value['questions']]==4){blah blah blah};
but the problem I am having is that the value of $value['questions'] is q1 but I need the q1 to be a string (i.e. inside quotes '') in the $results section of the code, so the $results element should look like this...
if($results['q1']==4){blah blah blah};
currently it looks like this
if($results[q1]==4){blah blah blah};
Make sense?
Thanks again for the help.
Hi all,
I hope there is a simple solution!
I have a variable:
$results['q1'];
Is it possible to have the 'q1' element as a variable, something like this:
$results['$i[question]'];
Have not been able to find a solution on Google and researching the PHP manuals...
Anyone got a suggestion/ solution?
Thanks,
Homer.
Yes, it is possible to use a variable as indice, when accessing an array element.
As an example, consider this portion of code :
$results = array(
'a' => 'sentence a',
'b' => 'hello !',
);
$indice = 'a';
echo $results[$indice];
Which will give the following output :
sentence a
Here, $indice is a quite simple variable, but you could have used whatever you wanted between the [ and ], like, for instance :
functions : $results[ my_function($parameter) ]
array element : $result[ $my_array['indice'] ]
Which seems to be what you want to do ?
object property : $result[ $obj->data ]
...
Basically, you can use pretty much whatever you want there -- as long as it evaluates to a scalar value (i.e. a single integer, string)
In your specific case, you could have $results declared a bit like this :
$results = array(
'q1' => 'first question',
'q2' => 'second question',
);
And $i would be declared this way :
$i = array(
'question' => 'q1'
);
Which means that $i['question'] would be 'q1', and that the following portion of code :
echo $results[ $i['question'] ];
Would get you this output :
first question
Edit : To answer the specific words you used in the title of your question, you could also use what's called variable variable in PHP :
$variable = 'a';
$indice = 'variable';
echo $results[ $$indice ];
Here :
$indice is 'variable'
and $$indice is 'a'
which means you'll get the same output as before
And, of course, don't forget to read the Arrays section of the PHP manual.
The Why is $foo[bar] wrong? paragraph could be of interest, especially, considering the example you firt posted.
Edit after the edit of the OP :
If $value['questions'] is 'q1', then, the two following portions of code :
if($results[$value['questions']]==4){blah blah blah}
and
if($results['q1']==4){blah blah blah}
should do exactly the same thing : with $results[$value['questions']], the $value['questions'] part will be evaluated (to 'q1') before the rest of the expression, and that one will be the same as $results['q1'].
As an example, the following portion of code :
$results = array(
'q1' => 4,
'q2' => 6,
);
$value = array('questions' => 'q1');
if($results[$value['questions']]==4) {
echo "4";
}
Outputs 4.
You can do:
$results[$i['question']];
This will first access the array $i to get the value corresponding to the key 'question'. That value will be used as the key into the array $results.
Your way: $results['$i[question]'];
is actually trying to get the value corresponding to the key '$i[question]' in the array $results. Since the key is in single quote, variable interpolation does not happen and the entire string is treated literally.
Alternatively you can also do:
$results["$i[question]"]; // using double quotes also works.
Example:
$arr1 = array('php' => 'zend', 'java' => 'oracle');
$arr2 = array('p' => 'php', 'j' => 'java');
echo $arr1[$arr2['p']]; // prints zend.
echo $arr1["$arr2[p]"]; // prints zend.
<?php
$result['q1'];
// is equivalent to
$index = 'q1';
$result[ $index ];
Now $index can be as complex as you want it to be. For example something like this is also possible:
$result[ 'q' . round( $someArray[$i] / 2 ) ];
CODE
<?php
$results = array(
'q1' => 'This is a result called q1.',
'q2' => 'So, can you access this?',
'$i[question]' => 'This is a result called $i[question]',
);
$i = array(
'question' => 'q2',
'answer' => 'Yes.'
);
echo '<pre>';
echo $results['q1'] . "\n"; // Using Array's is easy -
echo $results['$i[question]'] . "\n"; // all you gotta do is make sure
echo $results[$i['question']] . "\n"; // that you understand how
echo $i['answer']; // the keys work.
?>
OUTPUT
This is a result called q1.
This is a result called $i[question]
So, can you access this?
Yes.