如何将数组与PHP Laravel合并?

时间:2019-11-05 09:00:55

标签: php laravel

我克隆了带有输入组准备的HTML。未选中某些复选框和单选按钮。我要输入选定的电子邮件。

我尝试了很多方法。

array_merge()

array_combine()

array_push()

array_merge_recursive()

但是这些都不起作用。或者我不知道如何让他们工作。

HTML

<div class="form-group">
    <label for="name">E-posta</label>
    <div class="input-group">
        <input type="email" class="form-control email-address" name="email[]" placeholder="E-Posta giriniz">
        <div class="btn-group">
            <label class="btn btn-default">
                <input class="primary-radio" type="radio" name="primary[]" checked autocomplete="off"> <span
                    class="fas fa-star"></span>
            </label>
            <label class="btn btn-default">
                <input class="ban-checkbox" type="checkbox" name="ban[]" autocomplete="off"> <span
                    class="fas fa-ban"></span>
            </label>
            <label class="btn btn-default">
                <input class="invalid-checkbox" type="checkbox" name="invalid[]" autocomplete="off"> <span
                    class="fas fa-exclamation-circle"></span>
            </label>
        </div>
    </div>
</div>

PHP

public function add(Request $request)
{
    $emails = $request->input('email');
    $primary = $request->input('primary');
    $ban = $request->input('ban');
    $invalid = $request->input('invalid');

    $emailAddresses = array();

    foreach ($emails as $emailKey => $emailValue) {
        $emailAddresses[$emailKey] = [
            'emailAddress' => $emailValue,
            'invalid' => $invalid,
            'lower' => $emailAddresses,
            'ban' => $ban,
            'primary' => $primary
        ];
    }
    dd($emailAddresses);
}

输出

array:3 [▼
  0 => array:5 [▼
    "emailAddress" => "dodis@live.com"
    "invalid" => null
    "lower" => "dodis@live.com"
    "ban" => array:2 [▼
      0 => "on"
      1 => "on"
    ]
    "primary" => array:1 [▼
      0 => "on"
    ]
  ]
  1 => array:5 [▼
    "emailAddress" => "test@live.com"
    "invalid" => null
    "lower" => "test@live.com"
    "ban" => array:2 [▼
      0 => "on"
      1 => "on"
    ]
    "primary" => array:1 [▼
      0 => "on"
    ]
  ]
  2 => array:5 [▼
    "emailAddress" => "bundayok@live.com"
    "invalid" => null
    "lower" => "bundayok@live.com"
    "ban" => array:2 [▼
      0 => "on"
      1 => "on"
    ]
    "primary" => array:1 [▼
      0 => "on"
    ]
  ]
]

这样的输出来了。不应该那样这是我想要的示例。

0: {
        emailAddress: "bilgi@ekinciler.com.tr"
        invalid: false
        lower: "bilgi@ekinciler.com.tr"
        optOut: false
        primary: true
    }
1: {
        emailAddress: "muhasebe@ekinciler.com"
        invalid: false
        lower: "muhasebe@ekinciler.com"
        optOut: false
        primary: false
    }

对不起,我的英语。我希望我可以。如果您有帮助,我会很高兴。

1 个答案:

答案 0 :(得分:3)

尝试以下代码,

我所做的是在每个循环中添加数组索引以获取该索引的正确值,这里是您的

keyExtractor={this.keyExtractor}

是数组本身,因此对于第一个数组数据,您需要0索引。同样适用于所有数组。

"ban" => array:2 [▼
  0 => "on"
  1 => "on"
]