I have this type of array coming back:
Array
(
[data(0)] => somevalue
[data(1)] => somevalue
[data(2)] => somevalue
)
And I need converted to this:
Array (
[data] => Array (somevalue
[0] => somevalue
[1] => somevalue
[2] => somevalue
)
)
Keep in mind there can be other keys, so simply running a for loop on the count and feeding each value in is not an option.
I thought I would really simplify things by posting the simple example above, but I guess that didn’t tell enough of the story.
The data is a string back from PayPal. PayPal has a function called deformatNVP() which does the initial job of putting this in to an array, however it’s not an array that PHP can handle. It can look like this:
Array(
[responseEnvelope.ack] => somevalue
[responseEnvelope.timestamp] => somevalue
[responseEnvelope.build] => somevalue
[responseEnvelope.correlationId] => somevalue
)
It can also have something like:
Array(
[personalData(0)] => somevalue
[personalData(1)] => somevalue
[personalData(2)] => somevalue
)
That’s completely ugly, so the first step below fixes the dotted arrays, but I am left with these keys with parenthesis to deal with.
$data = array();
foreach ($array as $key => $value) {
$subkey = "";
$_keys = explode('.', $key);
if(count($_keys) > 1){
$key = $_keys[0];
$subkey = $_keys[1];
}
if(preg_match("/([0-9]+)/", $key, $matches)){
$key = preg_replace("/\([0-9]+\)/", "", $key);
$data[$key][$matches[0]][$subkey] = $value;
}
elseif($subkey)
$data[$key][$subkey] = $value;
else
$data[$key] = $value;
}
return $data;
If something
.can appear, sometimes other things can appear too. This specification should be clear enough before developing any algorithm to parse it.So far It can be done by looping over each element and splitting information using
preg_splitfunction. Following code put the resultant array in$resultvariable.See http://ideone.com/CJHHZ
Remember it just splits the string with non word characters (
\W).\Wmatches any characters other thana-z,A-Z,0-9and_.