Reputation: 13005
I'm having few arrays as follows. Actually I'm having too many such arrays but for your reference I've printed only few of them:
Array
(
[0] => lineItemData
[1] => name
)
Array
(
[0] => lineItemData
[1] => startDate
)
Array
(
[0] => lineItemData
[1] => endDate
)
Array
(
[0] => lineItemData
[1] => frequencyCapping
[2] => interval
)
Array
(
[0] => lineItemData
[1] => frequencyCapping
[2] => amount
)
Array
(
[0] => orderId
)
Array
(
[0] => isExternal
)
Now you can observe in man of the above arrays key value [lineItemData]
is common and it is present at oth index. Now I want to create a new array where the key would be [lineItemData]
and other arrays which don't have a value [lineItemData]
present within themselves should be new keys and other keys should be keys under every key. My question may confuse you. So I'm printing below the desired output array
Array
(
[lineItemData] => Array
(
[name] =>
[startDate] =>
[endDate] =>
[frequencyCapping] => Array
(
[interval] =>
[amount] =>
)
)
[orderId] =>
[isExternal] =>
)
Upvotes: 1
Views: 60
Reputation: 37365
You can do this with:
$data = [
['lineItemData', 'name'],
['lineItemData', 'startDate'],
['lineItemData', 'endDate'],
['lineItemData', 'frequencyCapping', 'interval'],
['lineItemData', 'frequencyCapping', 'amount'],
['orderId'],
['isExternal']
];
$result = [];
$pointer = &$result;
foreach($data as $keys)
{
foreach($keys as $key)
{
if(is_array($pointer) && !array_key_exists($key, $pointer))
{
$pointer[$key] = null;
}
$pointer = &$pointer[$key];
}
$pointer = &$result;
}
End result will look like:
array(3) {
["lineItemData"]=>
array(4) {
["name"]=>
NULL
["startDate"]=>
NULL
["endDate"]=>
NULL
["frequencyCapping"]=>
array(2) {
["interval"]=>
NULL
["amount"]=>
NULL
}
}
["orderId"]=>
NULL
["isExternal"]=>
NULL
}
Upvotes: 2
Reputation: 410
Maybe like so?
<?php
$super['lineItemData']['name'] = NULL;
$super['lineItemData']['startDate'] = NULL;
$super['lineItemData']['endDate'] = NULL;
$super['lineItemData']['frequencyCapping']['interval'] = NULL;
$super['lineItemData']['frequencyCapping']['amount'] = NULL;
$super['orderId'] = NULL;
$super['isExternal'] = NULL; ?>
I'm sure someone will get crafty and find a way to make this happen in one array
statement. I like this because it's easier for me to manage.
Upvotes: 0