简体   繁体   English

PHP 数组 - 从数组创建数组?

[英]PHP array - create an array from an array?

Hello I have POST array that looks like this,你好,我有一个看起来像这样的 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 
)

I wanting to create an new array where I would get the first email_address, firstname, and surname into an array, deal with that data and then proceed to the next email-address, firstname and surname.我想创建一个新数组,将第一个电子邮件地址、名字和姓氏放入一个数组中,处理该数据,然后继续处理下一个电子邮件地址、名字和姓氏。

Is this possible?这可能吗? I have tried this code,我试过这段代码,

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

however that code just produces this,然而该代码只是产生这个,

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

What do I need to do?我需要做什么?

You could try:你可以试试:

foreach($_POST as $key=>$value)
{
    $count=0;
    foreach($value as $val)
    {
        $newArray[$count++]=Array($key=>$val);
    }
}
$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]
  );
}

or (if the numeric indices have any meaning)或(如果数字索引有任何意义)

$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]
  );
}

You only need to re-order the elements into the $_POST array:您只需要将元素重新排序到$_POST数组中:

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

With the data you provided, it will give you this in the $users array:使用您提供的数据,它将在$users数组中为您提供:

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

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

Elements in $_POST that are not an array are ignored and filtered out. $_POST中不是数组的元素将被忽略并过滤掉。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM