简体   繁体   中英

PHP Replace keyword from key-value in multidimension array using string_replace

I have a multidimensional array like this

Array
(

    [0] => Array
        (
            [0] => Foo
            [1] => Bar
            [2] => I like foobar
            [3] => 09/09/2014
        )

    [1] => Array
        (
            [0] => Foo2
            [1] => Bar2
            [2] => Very much
            [3] => 10/09/2014
        )
)

keys array which looks like this

Array
    (
        [0] => From
        [1] => To
        [2] => Text
        [3] => Schedule Date
    )

and a message is a string variable

$message = "Hi {To} message is from {From} come get {Text}.

My question is how do I replace the keywords between {$key} for all the array values at the same time to produce a new $messages array containing the messages with keywords replaced?

This has to be done dynamically and not hard coded because different values will be used every time.

From php.net : mixed str_replace ( mixed $search , mixed $replace , mixed $subject [, int &$count ] )

So assuming you have:

Array1 (original): $arr1
Array2 (replace): $arr2

You could do:

foreach($arr2 as $key => $value) 
{
    $newMessage = str_replace ($arr1[$key], $value, $message, 1 );
}

Here is some commented code for you. This should work for you as long as the number of keys matches the number of elements in your input array. This also assumes your placeholders match your key names.

//input data    
$inputs = array();

$inputs[0][] = 'Foo';
$inputs[0][] = 'Bar';
$inputs[0][] = 'I like foobar';
$inputs[0][] = '09/09/2014';

$inputs[1][] = 'Foo2';
$inputs[1][] = 'Bar2';
$inputs[1][] = 'Very much';
$inputs[1][] = '10/09/2014';

//keys for the input data
$keys = array('From', 'To', 'Text', 'Schedule Date');

//message template
$message = "Hi {To} message is from {From} come get {Text}.";

$messages = array();

//Loop through the input data
foreach($inputs as $input) {
   $input = array_combine($keys, $input); //give input array our custom keys

   $userMessage = $message; //create a copy of the message template

   //Loop through the values replacing `{$key}` with $value
   foreach($input as $key=>$value) { 
       $userMessage = str_replace('{'.$key.'}', $value, $userMessage);
   }

   //Do something with the message
   $messages[] = $userMessage;

}

print_r($messages);

//Outputs:
//Array
//(
//    [0] => Hi Bar message is from Foo come get I like foobar.
//    [1] => Hi Bar2 message is from Foo2 come get Very much.
//)

Online demo here .

Best bet is to have the first array in this format:

Array
(
    [0] => Array
    (
        ['From'] => 'Foo',
        ['To'] => 'Bar',
        ['Text'] => 'Message text',
        ['Schedule_Date'] => '01/01/01',
    ),
    ...
)

Then you can do this in a loop:

$message = "Hi {To} message is from {From} come get {Text}.";
foreach ($array as $toSend) {
    $messageReplaced = $message;
    foreach ($toSend as $key => $value) {
        $messageReplaced = str_replace('{' . $key . '}', $value, $messageReplaced);
    }
    $this->mail->send($messageReplaced, $toSend['Schedule_Date']); // just an example
}

Assuming your title array is $titles , if the placeholders in your template were the same as the titles (eg {From} instead of From ) then you could trivially do the replacement with

foreach($data as $row) {
    $result = str_replace($titles, $row, $template);
    // now do something with $result
}

Since this is so convenient and the placeholders are almost the same as the titles, it's very tempting to convert the titles into placeholders first and then do the above:

$titles = ['From', 'To', 'Text'];
$placeholders = array_map(function($t) { return '{'.$t.'}'; }, $titles);
foreach($data as $row) {
    $result = str_replace($placeholders, $row, $template);
    // now do something with $result
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM