Yii Mailer PHP Error Array to string conversion - php

The problem is the checkboxlist selection which is a multiple select. When I remove the following mailer code from the controller, the form is emailed... '{serviceItem}' => $model->selection,
In the model, the following explode and implode is used for putting the selection into the db table correctly...
public function afterFind()
{
$this->selection=explode(',',$this->selection);
return true;
}
/*implode your selection */
public function beforeSave()
{
$this->selection=implode(',',$this->selection);
return true;
}
If implode beforeSave...
[quote="php manual"] Returns a string containing a string
representation of all the array elements in the same order, with the
glue string between each element.[/quote]
And the mailer $message = strtr returns a string from the array...
[quote="phpmanual"]strtr - If given two arguments, the second should be an array in the
form array('from' => 'to', ...). The return value is a string where all the occurrences of
the array keys have been replaced by the corresponding values...
$message = strtr ('Submitted on: {submissionDate}
Name: {firstName} {lastName}
Service Item: {serviceItem}
Visitor Comments: {message}', array(
'{submissionDate}' => $model->date,
'{firstName}' => $model->firstName,
'{lastName}' => $model->lastName,
'{serviceItem}' => $model->selection,
'{message}' => $model->comments));
Q. Why is there an error? and...
Q. What is the solution for the $model->selections to be sent in the email?

Q. Why is there an error?
Answer:
First strtr() expects the array to be of the form array('stringFROM'=>'stringTO') and not array('stringFROM'=>array(...)).
You are getting the second format(and hence the error) because $model->selection is an array, since you have done an explode() in afterFind().
afterFind() is called whenever you load a model with any of the find methods of CActiveRecord(i.e find(), findAll(), findByPk(), findByAttributes(), and so on), and if i am correct you are calling one of those of methods to get your current model.
Q. What is the solution for the $model->selections to be sent in the email?
Answer:
In this case you can simply do an implode() again, to get a string:
'{serviceItem}' => implode(',',$model->selection);

Related

Keeping array reference and adding something into that

In my very simple Laravel livewire component i have an array and when i try to add another data into that by clicking on a simple for example div i get fresh array with the last inserted data into that and i cant keep this array reference to append something data into that
<div wire:click="addNewSize"></div>
class SellerStoreNewProductComponent extends Component
{
public array $productSizes=[];
//...
public function addNewSize()
{
/* SOLUTION ONE */
//$this->productSizes[] = $this->productSizes + [str::random(10) => str::random(10)];
/* SOLUTION TWO */
//$this->productSizes[][]=array_push($this->productSizes, [str::random(10) => str::random(10)]);
/* SOLUTION THREE */
//array_push($this->productSizes, [str::random(10) => str::random(10)]);
dd($this->productSizes);
}
}
thanks in advance
If you're looking to add a key value pair to an existing array, you most likely want to use array_merge rather than array_push.
array_merge combines two arrays into a single array whereas array_push adds elements to an existing array.
public function addNewSize()
{
$this->productSizes = array_merge(
$this->productSizes, [Str::random(10) => Str::random(10)]
);
}
your current approaches will add a new index with new array data (previous value plus new value). so you just have to add new index to the array.
$this->productSizes['myKey'] = "myValue";

PHP doesn't find array elements

A library I use uses an array. Applying print_r to that array prints this:
Array
(
[*queueId] => 1
[*handle] => 9b875867b36d568483fb35fdb8b0bbf6
[*body] => First string in the TestQueue
[*md5] => c23ba714199666efbc1dcd5659bb0a0a
[*timeout] => 1408003330.6534
[*id] => 2
[*creationdate] => 2014-08-13 16:03:37
)
The library uses a magic getter on that array
public function __get($key)
{
if (!array_key_exists($key, $this->_data)) {
throw new Exception\InvalidArgumentException("Specified field \"$key\" is not in the message");
}
return $this->_data[$key];
}
When I try to access
$myObject->body
I run into the exception. In fact, the debugger shows that array_key_exists will return false while the _data array is available as printed above
The asterisk indicates that this array is a representation of an object, probably the original object property is protected.
http://php.net/manual/en/language.types.array.php#language.types.array.casting
As I explained in the comments, the array keys actually start with an asterisk. Since you can't call them using the regular syntax of $obj->*body (it'll cause a syntax error), you can use the following:
$myObject->{'*body'}
This should solve your problem.
Assuming that $myObject is the array you are talking from:
You can't access arrays with ->, use $myObject['*body'] instead. (And you should as well change the name to $myArray, for example)
As #MarkBaker stated in the comment of my question, the problem was that I was serializing an object with private properties to the array. The asterisk were marks that these properties were private.

Laravel returning null value with where method (if variable is passed)

I'm trying to use a where method in laravel query. i have a string containing two values (separated by comma). I need to search with value that is after the comma. So i used explode php function to make an array . So I get an array containing two key-value pairs. i want to use 2nd value to search database. So i'm storing the second value in a variable and then passing that variable in the where method. But it's returning blank collection object
Here's the code
$vehicles_name_trim_ar = explode(',', Input::get('vehicles_name_trim'));
print_r of $vehicles_name_trim_ar is
Array
(
[0] => A3
[1] => 2.0T Premium Automatic
)
//storing both values in seperate variable
$model_name = $vehicles_name_trim_ar[0];
$model_trim = $vehicles_name_trim_ar[1];
$model = Model::where('model_trim', $model_trim)->get();
It's returning blank result. However if i'm proving static value, it return the result
$model = Model::where('model_trim', "2.0T Premium Automatic")->get();
What am i doing wrong?
You have a space at the start of the second value. try this:
$model_name = trim($vehicles_name_trim_ar[0]);
$model_trim = trim($vehicles_name_trim_ar[1]);

Database logging in Zend Framework 2: wrong "extra" column name

I want to save log entries to my MySQL database from Zend Framework 2. I am using Zend\Log\Logger with a Zend\Log\Writer\Db writer. By supplying the writer with an array, one can choose which columns to save what data to (e.g. timestamp into a "log_date" column) and which data to save. Here is what I am doing:
$logger = new Zend\Log\Logger();
$mapping = array(
'timestamp' => 'timestamp_column',
'priority' => 'priority_column',
'message' => 'message_column',
'extra' => 'extra_column'
);
$logger->addWriter(new Zend\Log\Writer\Db($dbAdapter, 'table_name', $mapping));
$logger->err('some message', array('some extra information'));
The problem I am facing is that the array of column names and their values contain an incorrect column name for the "extra" column. Based on the array above, it should be inserting the value "some extra information" into the "extra_column" column. The problem is that the Zend\Log\Writer\Db class is using the letter "e" as the name of the extra column. This comes from the first letter of "extra_column" in my array above. For some reason, it is taking the first letter of "extra_column" and using it as the column name instead of the entire value.
I took a look at the source code. The mapEventIntoColumn method is being used to get the column names and values as an array. I copied in the relevant part of the method below.
// Example:
// $event = array('extra' => array(0 => 'some extra information'));
// $columnMap = array('extra' => 'extra_column');
// Return: array('e' => 'some extra information')
// Expected (without looking at the code below): array('extra_column' => 'some extra information')
protected function mapEventIntoColumn(array $event, array $columnMap = null) {
$data = array();
foreach ($event as $name => $value) {
if (is_array($value)) {
foreach ($value as $key => $subvalue) {
if (isset($columnMap[$name][$key])) {
$data[$columnMap[$name][$key]] = $subvalue;
}
}
}
}
return $data;
}
The $event parameter is an array containing the same keys as my $mapping array in my first code snippet and the values for the log message. The $columnMap parameter is the $mapping array from my first code snippet (array values are column names).
What actually seems to happen is that because I am passing in extra information as an array (this is required), the inner foreach loop is executed. Here, $key is 0 (the index) so it is actually doing like this: $columnMap['extra'][0]. This gives the letter "e" (the first letter in "extra_column"), which is used as the column name, where it should be the entire column name instead.
I tried to supply my own key in the extra array when calling the log method, but the same happens. The official documentation shows no examples of usage of the extra parameter. I want to insert information that can help me debug errors into my table, so I would like to use it.
Is this a bug or am I missing something? It seems really strange to me! I hope I explained it well enough - it is quite tricky!
Since Daniel M has not yet posted his comment as an answer, I will refer you to his comment which solved the problem.

Declare Array Inside Function Call PHP

Hey just wondering if there is a simpler way to declare an array inside a function call besides array()
$setup = new setupPage();
$setup->setup(array(
type => "static",
size => 350
));
class setupPage {
public function setup($config){
echo $config[size] . $config[type];
}
}
Thanks :D
If you use PHP 5.4+ you can use the shorthand, however it makes no difference in performance, but in actuality may make it harder to read:
$setup->setup(['type' => 'static',
'size' => 350]);
Create a PHP program with an array (student) with the following
categories: student_id, student_name, student_address,
student_state, student_zip, and student_age. A function within
the program will accept all the values and restrict the data type
passed for each. The function creates the array and place the
values into the array. Display the values in the array. Use try/catch
to display an error message if one or more of the values are not the
proper data type.

Categories