0

Hello I have POST array that looks like this,

Array (
  [email_address] => Array ( 
    [0] => [email protected]  
    [1] => [email protected] 
  ) 
  [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] => [email protected] 
      [1] => [email protected]
  )
  [1] => Array ( 
      [0] => Simon 
      [1] => Simon2
  ) [2] => Array ( [0] => Ainley [1] => Ainley2 ) [3] => [4] => Save User ) 1

What do I need to do?

1
  • Something with the array data you've in your question does look wrong. I edited a bit in case it's NULL. Commented Jul 2, 2011 at 9:16

3 Answers 3

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

You could try:

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

You only need to re-order the elements into the $_POST array:

$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:

[0] => Array
    (
        [email_address] => [email protected]
        [firstname] => Simon
        [surname] => Ainley
    )

[1] => Array
    (
        [email_address] => [email protected]
        [firstname] => Simon2
        [surname] => Ainley2
    )

Elements in $_POST that are not an array are ignored and filtered out.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.