如何拆分数组并设置键名

时间:2017-03-04 02:59:59

标签: php arrays

我有一个这样的数据数组,通过表单传递给我的控制器。它是在javascript函数中收集的。它总是通过电子邮件发送名称,但可能有2套或100个。

array:10 [▼
  0 => "ken@email.com"
  1 => "Ken"
  2 => "robert@email.com"
  3 => "Robert"
  4 => "robert@email.com"
  5 => "Robert"
  6 => "mike@email.com"
  7 => "Mike"
]

我目前正在这样做

$recipients = array_chunk($recipients, 2);

array:5 [▼
  0 => array:2 [▼
      0 => "ken@email.com"
      1 => "Ken"
  1 => array:2 [▼
      0 => "robert@email.com"
      1 => "Robert"
  2 => array:2 [▼
      0 => "robert@email.com"
      1 => "Robert"
  3 => array:2 [▼
      0 => "mike@email.com"
      1 => "Mike"
]

我需要的是这个......

array:5 [▼
  0 => array:2 [▼
      email => "ken@email.com"
      name => "Ken"
  1 => array:2 [▼
      email => "robert@email.com"
      name => "Robert"
  2 => array:2 [▼
      email => "robert@email.com"
      name => "Robert"
  3 => array:2 [▼
      email => "mike@email.com"
      name => "Mike"
]

如何?谢谢!

2 个答案:

答案 0 :(得分:1)

您可以使用键将值重新添加回数组,并通过索引删除其副本。

   $recipients = array(
      0 => "ken@email.com",
      1 => "Ken",
      2 => "robert@email.com",
      3 => "Robert",
      4 => "robert@email.com",
      5 => "Robert",
      6 => "mike@email.com",
      7 => "Mike"
    );

    $recipients = array_chunk($recipients, 2);

    for ($i=0; $i < count($recipients); $i++)
    {
        $recipients[$i]['email'] = $recipients[$i][0];
        $recipients[$i]['name'] = $recipients[$i][1];
        unset($recipients[$i][0]);
        unset($recipients[$i][1]);
    }

这将导致以下输出:

Array
(
    [0] => Array
        (
            [email] => ken@email.com
            [name] => Ken
        )

    [1] => Array
        (
            [email] => robert@email.com
            [name] => Robert
        )

    [2] => Array
        (
            [email] => robert@email.com
            [name] => Robert
        )

    [3] => Array
        (
            [email] => mike@email.com
            [name] => Mike
        )

)

我希望它对你有所帮助。

答案 1 :(得分:0)

是的,你可以这样做。

<?php
$array = array(
"foo" => "bar",
"bar" => "foo",
100   => -100,
-100  => 100,
);
var_dump($array);
?>

使用自定义键添加到数组

<?php
$array= array();
$array[]='name=>bob';
var_dump($array);

Array docs