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
Related
In Postman, whenever I pass key isbns and values 0307951529;9780307951526 while doing dd($queryArray);. I get the correct output:
^ array:2 [
"isbn10" => "0307951529"
"isbn13" => "9780307951526"
]
However, on the isbns key, when I try to pass one value in Postman instead of two - I get an error that says: array_combine(): Argument #1 ($keys) and argument #2 ($values) must have the same number of elements. This is because I'm being reliant on array_combine($keysArray, $valuesArray); to do this but I feel like it's not a good approach.
What's a good way to do this so that optionally, one or two semicolon separated values can be accepted so an error won't get thrown?
Note: dd(urldecode($request->fullUrl())); displays the url correctly (provided this detail in case more information is needed).
$isbn = $request->get('isbns');
$keysArray = ['isbn10', 'isbn13'];
$valuesArray = explode(';', $isbn);
$queryArray = array_combine($keysArray, $valuesArray);
$queryParams = [
'api-key' => $apiKey,
'author' => $author,
'title' => $title,
'isbns' => [(object) $queryArray]
];
dd($queryParams);
// dd(urldecode($request->fullUrl()));
Assuming you just want to know what to do if only one param is passed in isbn then you can do this
$isbn = '234234;777777';
$keysArray = ['isbn10', 'isbn13'];
$valuesArray = explode(';', $isbn);
foreach($valuesArray as $i=>$val){
$queryArray[$keysArray[$i]] = $val;
}
print_r($queryArray);
RESULT
Array
(
[isbn10] => 234234
[isbn13] => 777777
)
Now if you only pass one param
$isbn = '234234';
$keysArray = ['isbn10', 'isbn13'];
$valuesArray = explode(';', $isbn);
foreach($valuesArray as $i=>$val){
$queryArray[$keysArray[$i]] = $val;
}
print_r($queryArray);
RESULT
Array
(
[isbn10] => 234234
)
But this does leave a lot of potential for problems as mentioned in the comments, like is it correct that the single param should be placed in isbn10 and also what happens of there are 3 parameter passed like `123;456;789'
I am trying to replace the value of $row['roles'] with an array:
$row['roles'] = array(
"admin" => true,
"user" => true
);
Or
$row['roles'] = array("admin", "user"); // I think this is not posible, since php autogenerates the index keys.
This is the code I have that is not working for me:
$row['roles'] = '["admin","user"]';
$roles = json_decode($row['roles'], true);
foreach($roles as $role){
$row['roles'][$role] = true; // Warning illegal string offset 'admin'
}
var_dump($row['roles']); // string '1"admin","user"]' (length=16)
Does anyone have any idea how to generate such array from the json string?
I have also tried generating the array with explode, but all I get is an indexed array array(1=>admin,2=>user)
I would like to do a if(isset($row['admin']) check.
The reason why you have an error "Warning illegal string offset 'admin'" is that your array is not initialized as key => value array, so you can't use "admin" as a key.
Just reinitialize your array with this : $row['roles'] = [];
And your code will be working.
$row['roles'] = '["admin","user"]';
$roles = json_decode($row['roles'], true);
$row['roles'] = [];
foreach($roles as $role){
$row['roles'][$role] = true;
}
var_dump($row['roles']);
But depending on your real needs, I think that it should be really more simple.
I try to write a string into a variable in between an array
if ($row_klasse['RabKlNummerVK'] != ''){
$headerrabklasse = '\'Rabatt\'\=\>\'price\'\,';
}
else {$headerrabklasse = '';}
then I want to write the variable $headerrabklasse in:
$writer = new XLSXWriter();
$writer->writeSheetHeader (Preisliste, array(
'Marke'=>'string',
'Range'=>'string',
'Artikelnummer'=>'string',
'Bezeichnung'=>'string',
'EAN'=>'string',
'kg netto'=>'zahl3',
'VE'=>'string',
'Steuer'=>'string',
'Listenpreis'=>'euro',
$headerrabklasse
'Nettopreis'=>'price3',
'UVP'=>'price'),
['auto_filter'=>true, 'widths'=>[20,50,15,45,15,8,8,8,8,8],
'font-style'=>'bold', 'fill'=>'#eee',
'freeze_rows'=>1,
'freeze_columns'=>0] );
And I always get an error...
HAs anybody an idea?
In PHP you can easily append data to array like this:
//Define array with default values
//BTW: if you work with PHP >= 5.4 better to use [] instead of array()
$sheetHeaders = array(
'Marke'=>'string',
'Range'=>'string',
'Artikelnummer'=>'string',
'Bezeichnung'=>'string',
'EAN'=>'string',
'kg netto'=>'zahl3',
'VE'=>'string',
'Steuer'=>'string',
'Listenpreis'=>'euro',
'Nettopreis'=>'price3',
'UVP'=>'price'
);
if ($row_klasse['RabKlNummerVK'] != ''){
//Here you append data to existing array in format: array[key] = value
$sheetHeaders['Rabatt'] = 'price';
}
//Then use fulfilled array as you want
$writer->writeSheetHeader ($preisliste, $sheetHeaders);
Your array takes keys and values, so you need to write a key name, and pass the variable as a value. I also noticed you were mixing Array declarations. In PHP you can call an array like this:
Array(el1, el2, ...)
or like this:
[el1, el1, ...]
Either one is fine, but for best practices you want to pick one and stick with it.
$writer->writeSheetHeader(Preisliste, [
'Marke'=>'string',
...
'MyNewKeyName' => $headerrabklasse,
...
],
[
...
]
);
I guess you wan't to do this one:
if ($row_klasse['RabKlNummerVK'] != '') {
$headerrabklasse = ['Rabatt' => 'price'];
}
else {$headerrabklasse = [];}
You could do stuff like that:
$writer->writeSheetHeader (Preisliste, array_merge(array(
'Marke'=>'string',
'Range'=>'string',
'Artikelnummer'=>'string',
'Bezeichnung'=>'string',
'EAN'=>'string',
'kg netto'=>'zahl3',
'VE'=>'string',
'Steuer'=>'string',
'Listenpreis'=>'euro',
'Nettopreis'=>'price3',
'UVP'=>'price'),
['auto_filter'=>true, 'widths'=>[20,50,15,45,15,8,8,8,8,8],
'font-style'=>'bold', 'fill'=>'#eee',
'freeze_rows'=>1,
'freeze_columns'=>0]), $headerrabklasse);
I am recently facing a practical problem.I am working with ajax form submission and there has been some checkboxes.I need all checkboxes with same name as key value pair.Suppose there is 4 checkboxes having name attribute =checks so i want something like $arr['checks'] = array(value1, value2, ...)
So i am getting my ajax $_POST code as suppose like: name=alex&checks=code1&checks=code2&checks=code3
I am using below code to make into an array
public function smdv_process_option_data(){
$dataarray = array();
$newdataarray = array();
$new = array();
$notices = array();
$data = $_POST['options']; // data received by ajax
$dataarray = explode('&', $data);
foreach ($dataarray as $key => $value) {
$i = explode('=', $value);
$j = 1;
if(array_key_exists($i[0], $newdataarray)){
if( !is_array($newdataarray[$i[0]]) ){
array_push($new, $newdataarray[$i[0]]);
}else{
array_push($new, $i[1]);
}
$newdataarray[$i[0]] = $new;
}else{
$newdataarray[$i[0]] = $i[1];
}
}
die($newdataarray);
}
Here i want $newdataarray as like below
array(
'name' => 'alex',
'checks => array(code1, code2, code3),
)
But any how I am missing 2nd value from checks key array.
As I see it you only need to do two explode syntaxes.
The first on is to get the name and here I explode on & and then on name= in order to isolate the name in the string.
The checks is an explode of &checks= if you omit the first item with array_slice.
$str = 'name=alex&checks=code1&checks=code2&checks=code3';
$name = explode("name=", explode("&", $str)[0])[1];
// alex
$checks = array_slice(explode("&checks=", $str), 1);
// ["code1","code2","code3"]
https://3v4l.org/TefuG
So i am getting my ajax $_POST code as suppose like: name=alex&checks=code1&checks=code2&checks=code3
Use parse_str instead.
https://php.net/manual/en/function.parse-str.php
parse_str ( string $encoded_string [, array &$result ] ) : void
Parses encoded_string as if it were the query string passed via a URL and sets variables in the current scope (or in the array if result is provided).
$s = 'name=alex&checks=code1&checks=code2&checks=code3';
parse_str($s, $r);
print_r($r);
Output
Array
(
[name] => alex
[checks] => code3
)
You may think this is wrong because there is only one checks but technically the string is incorrect.
Sandbox
You shouldn't have to post process this data if it's sent correctly, as that is not included in the question, I can only make assumptions about it's origin.
If your manually creating it, I would suggest using serialize() on the form element for the data for AJAX. Post processing this is just a band-aid and adds unnecessary complexity.
If it's from a source outside your control, you'll have to parse it manually (as you attempted).
For example the correct way that string is encoded is this:
name=alex&checks[]=code1&checks[]=code2&checks[]=code3
Which when used with the above code produces the desired output.
Array
(
[name] => alex
[checks] => Array
(
[0] => code1
[1] => code2
[2] => code3
)
)
So is the problem here, or in the way it's constructed...
UPDATE
I felt obligated to give you the manual parsing option:
$str = 'name=alex&checks=code1&checks=code2&checks=code3';
$res = [];
foreach(explode('&',$str) as $value){
//PHP 7 array destructuring
[$key,$value] = explode('=', $value);
//PHP 5.x list()
//list($key,$value) = explode('=', $value);
if(isset($res[$key])){
if(!is_array($res[$key])){
//convert single values to array
$res[$key] = [$res[$key]];
}
$res[$key][] = $value;
}else{
$res[$key] = $value;
}
}
print_r($res);
Sandbox
The above code is not specific to your keys, which is a good thing. And should handle any string formatted this way. If you do have the proper array format mixed in with this format you can add a bit of additional code to handle that, but it can become quite a challenge to handle all the use cases of key[] For example these are all valid:
key[]=value&key[]=value //[key => [value,value]]
key[foo]=value&key[bar]=value //[key => [foo=>value,bar=>value]]
key[foo][]=value&key[bar][]=value&key[bar][]=value //[key => [foo=>[value]], [bar=>[value,value]]]
As you can see that can get out of hand real quick, so I hesitate to try to accommodate that if you don't need it.
Cheers!
$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