PHP array - create an array from an array?
Hello I have POST array that looks like this,
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.开发者_如何学C
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?
$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 could try:
foreach($_POST as $key=>$value)
{
$count=0;
foreach($value as $val)
{
$newArray[$count++]=Array($key=>$val);
}
}
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] => 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.
精彩评论