2017-03-04 26 views
-1

我有一個像這樣的數據數組,通過表單傳遞給我的控制器。它被收集在一個JavaScript函數中。它總是會通過電子郵件發送的名稱,但可能有2套或100如何分割數組並設置鍵名

array:10 [▼ 
    0 => "[email protected]" 
    1 => "Ken" 
    2 => "[email protected]" 
    3 => "Robert" 
    4 => "[email protected]" 
    5 => "Robert" 
    6 => "[email protected]" 
    7 => "Mike" 
] 

目前,我正在做這個

$recipients = array_chunk($recipients, 2); 

array:5 [▼ 
    0 => array:2 [▼ 
     0 => "[email protected]" 
     1 => "Ken" 
    1 => array:2 [▼ 
     0 => "[email protected]" 
     1 => "Robert" 
    2 => array:2 [▼ 
     0 => "[email protected]" 
     1 => "Robert" 
    3 => array:2 [▼ 
     0 => "[email protected]" 
     1 => "Mike" 
] 

我需要的,雖然是這樣...

array:5 [▼ 
    0 => array:2 [▼ 
     email => "[email protected]" 
     name => "Ken" 
    1 => array:2 [▼ 
     email => "[email protected]" 
     name => "Robert" 
    2 => array:2 [▼ 
     email => "[email protected]" 
     name => "Robert" 
    3 => array:2 [▼ 
     email => "[email protected]" 
     name => "Mike" 
] 

如何?謝謝!

+0

所以,如果總有電子郵件地址和名字將永遠是偶數? –

+0

除非我正在查詢API,但據我所知,還沒有發生。 – ahackney

回答

1

您可以使用鍵將數值重新添加到數組中,並通過索引刪除其重複項。

$recipients = array(
     0 => "[email protected]", 
     1 => "Ken", 
     2 => "[email protected]", 
     3 => "Robert", 
     4 => "[email protected]", 
     5 => "Robert", 
     6 => "[email protected]", 
     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] => [email protected] 
      [name] => Ken 
     ) 

    [1] => Array 
     (
      [email] => [email protected] 
      [name] => Robert 
     ) 

    [2] => Array 
     (
      [email] => [email protected] 
      [name] => Robert 
     ) 

    [3] => Array 
     (
      [email] => [email protected] 
      [name] => Mike 
     ) 

) 

我希望它幫你。

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