I want to create and initialize a multidimensional array with known possible keys for the second dimension but no values.
This array will store event_ids
(populated dynamically) and for each event_id
an array having exactly four different counts (also filled dynamically).
Structure I want to create
Array
(
[0] => Array =================> This index will be the event_id
(
[invitation_not_sent_count] =>
[no_response_yet_count] =>
[will_not_attend_count] =>
[will_attend_count] =>
)
)
What I did so far?
$DataArray = array();
$DataArray[] = array('invitation_not_sent_count' => '',
'no_response_yet_count' => '',
'will_not_attend_count' => '',
'will_attend_count' => '');
And inside the loop I am populating data dynamically like:
$DataArray[$result->getId()]['no_response_yet_count'] = $NRCount;
What I get is:
Array
(
[0] => Array
(
[invitation_not_sent_count] =>
[no_response_yet_count] =>
[will_not_attend_count] =>
[will_attend_count] =>
)
[18569] => Array
(
[no_response_yet_count] => 2
)
[18571] => Array
(
[no_response_yet_count] => 1
)
)
What I want is that if a value is not available in the iteration, its entry should be empty as defined at initialization time. So if all other counts are empty in the data except no_response_yet_count
, the array should be:
Expected Output
Array
(
[18569] => Array
(
[invitation_not_sent_count] =>
[no_response_yet_count] => 2
[will_not_attend_count] =>
[will_attend_count] =>
)
[18571] => Array
(
[invitation_not_sent_count] =>
[no_response_yet_count] => 1
[will_not_attend_count] =>
[will_attend_count] =>
)
)
I usually resort to a mapping function at that point:
function pre_map(&$row) {
$row = array
(
'invitation_not_sent_count' => '',
'no_response_yet_count' => '',
'will_not_attend_count' => '',
'will_attend_count' => ''
);
}
Then in the while/for loops:
{
$id = $result->getId();
if (!isset($DataArray[$id])) { pre_map($DataArray[$id]); }
$DataArray[$id]['no_response_yet_count'] = $NRCount;
}
The if (!isset($DataArray[$id]))
is to make sure it doesn't wipe out the same index row, in case you happen to re-loop on the same ID. Thus, it will only map it once, then never again in the loop.
There are some other one-line shortcuts like maybe even using array_map(), but I was showing the long version, for full flexibility just in case.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.