I am having a function which has an array in it. I wanted to call that function foo and use the $result indexes (text, html, attachments) in my script. Please help me with this since I am totally new to php. I am trying to call the array to the mail() method. and getting error saying string expected and it id array. How can I insert the array to the relevant mail method.
function foo($a)
{
if (is_resource($b))
{
$result = array
(
'text' => null,
'html' => null,
'attachments' => array(),
);
}
return $result;
}
You cannot pass an array to the mail function as it is expecting just strings. If you want the text of the email to be $result['text'], try
mail ($to, $subject, $result['text']
However, it looks like what are you trying is to have an array populate the attachments and content of an email. There's nothing like that out from the box in PHP. You may have to look for some third parties library. SwiftMailer maybe what you want.
Related
Is it possible to make something like that:
$array = array('id' => '5', 'something_else' => 'hi');
function some_function($id, $something_else)
{
echo $something_else;
}
some_function(extract($array));
This code is giving me true/false and not $id,$something_else, etc..
It is important for me to do something like that, because I have different list of variables for each function ( I'm working on my ( let's call it ) "framework" and I want to pass list of variables instead of array with variables. This code is actually going in my router so it's not quite that simple, but in the end it comes to that ).
I assume you know how your array is built. So, why do not you just pass an array as a parameter and then use it in your function ?
If you do something like this you can access to your array's values :
echo $array['something_else'];
And build your function like this :
$array = array('id' => '5', 'something_else' => 'hi');
function some_function($an_array)
{
echo $an_array['something_else']; // value for something_else
}
some_function($array);
Or if you don't want to change function's parameters, call it like this :
some_function($array['id'], $array['something_else']);
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.
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);
I have a javascript client passing a parameter to a server function (I'm using ExtJS Direct). Sometimes the client sends a single object, sometimes it sends an array of objects.
Currently I'm using this EnsureArray function to ensure the parameter is an array, and then I do foreach:
// Wraps a non array variable with an array.
function EnsureArray( &$aVar )
{
if ( !is_array( $aVar ) )
$var = array( $aVar );
}
function Destroy( $aRecords )
{
// $aRecords might be a single object or an array of objects. Ensure it's wrapped as an array.
$this->EnsureArray( $aRecords );
foreach ( $aRecords as $aRecord )
{
sql( "UPDATE Groups SET deleted = true WHERE id = $aRecord->id LIMIT 1" );
}
return array(
'success' => true,
);
}
Is there a trick, neater way, one line that can do the same?
Edit: Since posting this question, I've found that ExtJS has an option to send all records wrapped in array.
You could try the following, instead of the function:
$aRecords = is_array($aRecords) ? $aRecords : array($aRecords);
That's probably the best way tbh, if you're not going to enforce that you're always being sent an array.
I would make the function Destroy require arrays as its parameter:
function Destroy(array $aRecords) { ... }
The client should then also always send arrays. If, for whatever reason, that is not possible, the code that is receiving the (non-)array from the client and is passing it on to Destroy() needs to be responsible for passing it along as an array, because it's the interface between the (non-compliant) client and the standardized function.
There's probably going to be one endpoint for each possible action the client can call, so you don't even need to figure out whether the data is an array or not, you simply know. I.e.:
// someaction.php
include 'destroy.php';
$data = json_decode($_POST['data']);
Destroy($data);
but:
// anotheraction.php
include 'destroy.php';
$data = json_decode($_POST['data']);
Destroy(array($data));
If the client erratically sends different formats to the same action, fix the client.
Simply typecast the variable to an array:
function Destroy( $aRecords )
{
foreach ( (array)$aRecords as $aRecord )
{
sql( "UPDATE Groups SET deleted = true WHERE id = $aRecord->id LIMIT 1" );
}
return array(
'success' => true,
);
}
See http://php.net/manual/en/language.types.type-juggling.php
The scenario: fetch an email template from the database, and loop through a list of recipients, personalising the email for each.
My email template is returned as a nested object. It might look a little like this:
object(stdClass) {
["title"] => "Event Notification"
["sender"] => "notifications#mysite.com"
["content"] => object(stdClass) {
["salutation"] => "Dear %%firstname%%,"
["body"] => "Lorem ipsum %%recipient_email%% etc etc..."
}
}
Then I loop through the recipients, passing this $email object to a personalise() function:
foreach( $recipients as $recipient ){
$email_body = personalise( $email, $recipient );
//send_email();
}
The issue, of course, is that I need to pass the $email object by reference in order for it to replace the personalisation tags - but if I do that, the original object is changed and no longer contains the personalisation tags.
As I understand, clone won't help me here, because it'll only create a shallow copy: the content object inside the email object won't be cloned.
I've read about getting round this with unserialize(serialize($obj)) - but everything I've read says this is a big performance hit.
So, two finally get to my two questions:
Is unserialize(serialize($obj)) a reasonable solution here?
Or am I going about this whole thing wrong? Is there a different way that I
can generate personalised copies of that email object?
You could add a __clone() method to your email class. Which is automatically called when an instance of this class is cloned via clone(). In this method you can then manually add the template.
Example:
class Email {
function __clone() {
$this->template = new Template();
}
}
.
unserialize(serialize($object)); // would be another solution...
Another more generic and powerful solution: MyCLabs\DeepCopy.
It helps creating deep copy without having to overload __clone (which can be a lot of work if you have a lot of different objects).
Recursive cloning can be done this way:
public function __clone(): void {
foreach(get_object_vars($this) as $name => $value)
if(is_object($value)) $this->{$name} = clone $value;
}
Not sure why it's not mentioned here, but the keyword clone before the object does exactly what it says.
Here's an example:
// Prepare shared stream data
$args = (object) [
'key' => $key,
'data_type' => $data_type,
'data' => clone $data_obj,
'last_update' => $last_update
];
setSharedStreamData($args);
// Object below will not change when data property
// is updated in setSharedStreamData function
print_r($data_obj);