在php中将字符串拆分为数组对象

时间:2017-02-15 18:14:52

标签: php arrays string object

我有一个这样的字符串:" abc@gmail.com; ABC,xyz @ gmail.com; XYZ"我想转换成数组boject。我怎样才能做到这一点? 以下是样本

$noactivity_noassignedto = "abc@gmail.com;ABC,xyz@gmail.com;XYZ";
$assignedto = explode(';', $noactivity_noassignedto);
$assignedto = array((object) array("Email" => $assignedto[0], "Name" => $assignedto[1]));
$fromadd = 'some@abc.com';
$fromname = 'somename';
/*sending mail here*/
$this->init()->setsubject($sub)->addto($assignedto)->setfrom($fromadd, $fromname)->send();

5 个答案:

答案 0 :(得分:1)

$noactivity_noassignedto = "abc@gmail.com;ABC,xyz@gmail.com;XYZ";
$elements = explode(',', $noactivity_noassignedto);
foreach ($elements as $element) {
    $dummy = explode(';', $element);
    $assignedto[] = (object)array("Email" => $dummy[0], "Name" => $dummy[1]);
}

答案 1 :(得分:1)

试试这段代码:

$noactivity_noassignedto = "abc@gmail.com;ABC,xyz@gmail.com;XYZ";
$assignedto = explode(',', $noactivity_noassignedto);

foreach ($assignedto as $recipient) {
    $tmp = explode(';', $recipient);
    $recipients[] = (object)array("Email" => $tmp[0], "Name" => $tmp[1]);
}
$recipients = (object)$recipients;

答案 2 :(得分:0)

这将生成您想要的对象数组

$noactivity_noassignedto = "abc@gmail.com;ABC,xyz@gmail.com;XYZ";
$assignedto = explode(',', $noactivity_noassignedto);

foreach($assignedto as $item) {
    list($email, $name) = explode(';', $item);
    $addresses[] = (object)['Name'=>$name, 'Email'=>$email];
}

print_r($addresses);

结果:print_r($addresses);

Array
(
    [0] => stdClass Object
        (
            [Name] => ABC
            [Email] => abc@gmail.com
        )

    [1] => stdClass Object
        (
            [Name] => XYZ
            [Email] => xyz@gmail.com
        )

)

答案 3 :(得分:0)

你需要两次爆炸

<script type="text/javascript" src="//code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script>
var positions = JSON.parse(localStorage.positions || "{}");
$(function () {
    var d = $("[class=draggable]").attr("class", function (i) {
        return "draggable_" + i
    })
    $.each(positions, function (id, pos) {
        $("#" + id).css(pos)
    })

    d.draggable({
        scroll: false,
        stop: function (event, ui) {
            positions[this.id] = ui.position
            localStorage.positions = JSON.stringify(positions)
        }
    });
});
</script>

答案 4 :(得分:-1)

你走在正确的道路上。您正在寻找将字符串拆分为数组的explode。 给定

$str = "abc@gmail.com;ABC";
$arr = explode($str, ';');

$ arr将是array('abc@gmail.com', 'ABC');

我认为您的问题是您要多次调用此问题。要做到这一点:

$str = "abc@gmail.com;ABC,def@gmail.com;DEF";
$people = explode($str, ',');
foreach ($people as $person) {
    $assigned_to = explode($person, ';');
    // rest of your code
}