【问题标题】:How to send a specific data from a multidimensional array in laravel如何从 laravel 中的多维数组发送特定数据
【发布时间】:2020-06-10 15:36:27
【问题描述】:

我有一个看起来像这样的多维数组

"user1@email.com" => array:2 [
    0 => {
        "product": "Product 1",
        "category": "Paint"
    },
    1 => {
        "product": "Product 2",
        "category": "Brushes"
    }
]
"user2@email.com" => array:1 [
    0 => {
        "product" => "Product 3",
        "category" => "Canves"
    }
]

我想要做的是仅通过电子邮件向用户发送属于其数组一部分的信息。例如:我想给 user1@email.com 发电子邮件 只有这些项目

0 => {
    "product": "Product 1",
    "category": "Paint"
},
1 => {
    "product": "Product 2",
    "category": "Brushes"
}

并发送电子邮件至 user2@email.com

0 => {
    "product" => "Product 3",
    "category" => "Canves"
}

我已经设法通过这样做来获取电子邮件

$keys = array_keys($array);

foreach($keys as $key)
{
    if($key != "")
    {
        Mail::to($key)->send(new ProductsEmail($array));
    }
}

但我在仅获取和发送属于该电子邮件地址的信息时遇到问题。

【问题讨论】:

  • 在您的foreach中,您需要声明键/值foreach($keys as $key => $value)并使用$值进行邮件Mail::to($key)->send(new ProductsEmail($value));

标签: laravel laravel-7


【解决方案1】:
$array = [
    "user1@email.com" => [
        0 => {
            "product" => "Product 1",
            "category" => "Paint"
        },
        1 => {
            "product" => "Product 2",
            "category" => "Brushes"
        }
    ],
    "user2@email.com" => [
        0 => {
            "product" => "Product 3",
            "category" => "Canves"
        }
    ]
];

foreach ($array as $key => $value) {
    $emailAddress = $key;
    $items = $value;

    echo '<div style="margin-bottom:20px;">'.$emailAddress.' has purchased :<br/>';

    foreach ($items as $item) {
        echo '- Product <strong>'.$item->product.'</strong> in category <strong>'.$item->category.'</strong><br/>';
    }

    echo '</div>';
}

【讨论】:

  • 这个答案提倡不良做法,例如内联 HTML、内联样式
  • @OsDev 这只是一个关于在哪里提取信息而不是实际答案的示例,OP 想要邮寄数据。
  • 他已经有了解析数据的视图,他只需要数组数据
  • 不,他在获取特定邮件的数据时遇到问题,而不是全部,所以我说这是获取正确数据的问题。 @OsDev
【解决方案2】:

我猜你没有数组中的值。请遵循此。

$temp = ['user1@email.com' => [ ['product'=> 'Product 1', 'category'=>'Paint'], ['product'=> 'Product 2', 'category'=>'Brushes']  ], 'user2@email.com' => [["product" => "Product 3", "category" => "Canves"]]];
$array = json_decode(json_encode($temp, true),true); // convert into multidimensional array 

foreach($array as $email => $products) {

    // please check this and change if required.
    echo '<pre>'; print_r($products); 
    Mail::to($email)->send(new ProductsEmail($products));

}

【讨论】:

    【解决方案3】:

    必须这样做,您要访问电子邮件密钥的值

    foreach ($array as $email => $products) {
        Mail::to($email)->send(new ProductsEmail($products));
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-10-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-27
      • 2022-01-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多