I have an array in the following format:
Array
(
[accountID] => Array
(
[0] => 412216
[1] => 396408
[2] => 522540
)
[mailBody] => Array
(
[0] => 'We are glad to have contact you'
[1] => 'Thank you for your cooperation'
[2] => 'One of our customer service representatives will contact you soon'
)
[mailAttachments] => Array
(
[0] => 'URL1'
[1] => 'URL1'
[2] => 'URL1'
)
)
This array pulls some informatio开发者_StackOverflow中文版n from a mailing box. I would like to extract each accountID with equivalent mailBody and mailAttachments as well. Your response is highly appreciated.
Not beautiful but works (if I understand your purpose correctly):
$mails = array();
for ($i = 0, $cnt = count($array['accountID']); $i < $cnt; $i++) {
$mails[] = array(
'accountId' => $array['accountID'][$i],
'mailBody' => $array['mailBody'][$i],
'mailAttachments' => $array['mailAttachments'][$i]
);
}
PHP has a function build in for this, names array_map
. If the callback is NULL
, a combination of the array like you need it is created. As I'm lazy, I'm using call_user_func_array
to pass the parameters to the function.
$array
is you array:
$arranged = call_user_func_array('array_map', array(NULL) + $array);
Use the array indexes.
$i = 0
$accountID[$i];
$mailBody[$i];
$mailAttachments[$i];
But a better design would be to wrap all of these variables into one array if possible. Something like:
$accounts = array();
$account = array(
"id" => "",
"mailBody" => "",
"mailAttachments" => "",
);
$accounts[] = $account;
$mails = array_map(function ($id, $body, $attachments) {
return compact('id', 'body', 'attachments');
}, $array['accountId'], $array['mailBody'], $array['mailAttachments']);
It's important to note that this syntax requires PHP 5.3.
This rearranges the array so all items belonging together are in an array. You can then loop through the array and do whatever you need with it.
foreach ($mails as $mail) {
// use $mail['id'], $mail['body'], $mail['attachments'] ...
}
精彩评论