PHP数组-从数组创建数组



你好,我有一个POST数组,看起来像这样,

Array (
  [email_address] => Array ( 
    [0] => simon@simonainley.info  
    [1] => simon2@simonainley.info 
  ) 
  [firstname] => Array ( 
    [0] => Simon 
    [1] => Simon2 
  ) 
  [surname] => Array ( 
    [0] => Ainley 
    [1] => Ainley2 
  ) 
  [companies_company_id] => NULL,
  [save_user] => Save User 
)

我想创建一个新的数组,将第一个电子邮件地址、名字和姓氏放入数组中,处理这些数据,然后转到下一个电子邮件地址,名字和姓氏。

这可能吗?我试过这个代码,

$newArray = array();
    foreach($_POST as $key => $value)  {
    $newArray[] = $value;
}

然而,该代码只是产生了这个,

Array (
  [0] => Array ( 
      [0] => simon@simonainley.info 
      [1] => simon2@simonainley.info
  )
  [1] => Array ( 
      [0] => Simon 
      [1] => Simon2
  ) [2] => Array ( [0] => Ainley [1] => Ainley2 ) [3] => [4] => Save User ) 1

我需要做什么?

$count = count($_POST['firstname']);
$result = array();
for ($i = 0; $i <= $count; $i ++) {
  $result[] = array(
    'email_address' => $_POST['email_address'][0],
    'firstname' => $_POST['firstname'][0],
    'lastname' => $_POST['lastname'][0]
  );
}

或者(如果数字索引有任何含义(

$result = array();
foreach (array_keys($_POST['email_address']) as $index) {
  $result[$index] = array(
    'email_address' => $_POST['email_address'][$index],
    'firstname' => $_POST['firstname'][$index],
    'lastname' => $_POST['lastname'][$index]
  );
}

您可以尝试:

foreach($_POST as $key=>$value)
{
    $count=0;
    foreach($value as $val)
    {
        $newArray[$count++]=Array($key=>$val);
    }
}

您只需要将元素重新排序到$_POST数组中:

$users = array();
foreach($_POST as $key => $values) {
    if (is_array($values)) {
        foreach($values as $index => $value) {
            $users[$index][$key] = $value;
        }
    }
}

根据您提供的数据,它将在$users阵列中为您提供以下信息:

[0] => Array
    (
        [email_address] => simon@simonainley.info
        [firstname] => Simon
        [surname] => Ainley
    )
[1] => Array
    (
        [email_address] => simon2@simonainley.info
        [firstname] => Simon2
        [surname] => Ainley2
    )

$_POST中不是数组的元素将被忽略并过滤掉。

相关内容

  • 没有找到相关文章

最新更新