【问题标题】:PHP Replace keyword from key-value in multidimension array using string_replacePHP使用字符串替换从多维数组中的键值替换关键字
【发布时间】:2014-10-07 00:11:09
【问题描述】:

我有一个这样的多维数组

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
    (
        [0] => From
        [1] => To
        [2] => Text
        [3] => Schedule Date
    )

消息是一个字符串变量

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

我的问题是如何同时替换所有数组值的{$key} 之间的关键字,以生成一个新的$messages 数组,其中包含替换关键字的消息?

这必须动态完成,而不是硬编码,因为每次都会使用不同的值。

【问题讨论】:

  • 数组之间有关系吗?第一个数组中的第 0 个元素是否总是 {from}
  • 我 array_slice() 第一个数组,这样我得到 2 个数组,一个用于关键字,另一个用于我要替换的值。本质上,关键字数组是数组 [0]。这有帮助吗?

标签: php arrays string laravel dynamic-arrays


【解决方案1】:

这里有一些注释代码供您参考。只要键的数量与输入数组中的元素数量匹配,这应该对您有用。这还假设您的占位符与您的键名匹配。

//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.
//)

在线演示here.

【讨论】:

    【解决方案2】:

    来自php.netmixed str_replace ( mixed $search , mixed $replace , mixed $subject [, int &$count ] )

    所以假设你有:

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

    你可以这样做:

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

    【讨论】:

      【解决方案3】:

      最好的办法是让第一个数组采用这种格式:

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

      然后你可以循环执行:

      $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
      }
      

      【讨论】:

      • 谢谢,您的回答类似于@cOle2。帮助很大
      • @zinyando 这是一个很好的庄园,通过单击答案左侧的 tick 图标来接受您使用过的答案(这对您有帮助) . upvote 其他好的答案或 downvote 完全不好的答案(在您收到至少 250 exp 之后)也是很好的庄园 - 通过点击 up/答案左侧的向下箭头图标。
      【解决方案4】:

      假设您的标题数组是 $titles,如果您模板中的占位符与标题相同(例如 {From} 而不是 From),那么您可以轻松地进行替换

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

      既然这样很方便,而且占位符几乎和标题一样,所以先把标题转换成占位符再做上面的操作是很有诱惑力的:

      $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
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-10-15
        • 1970-01-01
        • 2014-02-05
        • 1970-01-01
        • 1970-01-01
        • 2014-12-22
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多