I have the following snippet of a large array:
Array
(
[agreementTypes] => Array
(
[WS_PEAgreementType] => Array
(
[0] => Array
(
[description] => Blah blah blah
[type] => Contract Supply
)
[1] => Array
(
[description] => Standard
[type] => Standard
)
)
)
Any key with "WS_PE" in it is redundant. Some are different to the above and in different levels of the array. I would like to find any key containing "WS_PE", take its values, and assign them directly to the parent of the found "WS_PE" key.
The above snippet needs to be so:
Array
(
[agreementTypes] => Array
(
[0] => Array
(
[description] => Blah blah blah
[type] => Contract Supply
)
[1] => Array
(
[description] => Standard
[type] => Standard
)
)
Finding the key is easy in a for loop. But I'm stuck knowing the name and level of the main array the parent of found key is (recursively).
EDIT: Here is a recursive function I have written. It works in terms of keeping track of the name of the parent key, but not the level/location in the array:
class PISupport {
private $previousKey;
public function stripRedundantAspireTags($rawData) {
$returnArray = array();
foreach($rawData as $key => $data) {
if(false !== strpos($key, 'WS_PE')) {
// Want to remove this key and assign data to the previous key
$keyToUse = $this->previousKey;
} else {
// Just use the current key in the loop
$keyToUse = $key;
}
$this->previousKey = $key;
if(is_array($data)) {
$obj[$keyToUse] = $this->stripRedundantAspireTags($data); //RECURSION
} else {
$obj[$keyToUse] = $data;
}
}
return $returnArray;
}
}
UPDATE
Almost working example thanks to didierc. The one issue is somehow it's discarding all elements but the first element of the first level of the array. Logic bug somewhere: https://gist.github.com/anonymous/b2fe834209ad74502824