Reputation: 714
Using Sencha Touch (not important for the question), the beneath array of data is send to my PHP script.
["slider3"] => 1
["toggle3"] => 0
["text3"] => "text"
["slider8"] => 5
["toggle8"] => 0
["text8"] => "text"
["slider11"] => 4
["toggle11"] => 0
["text11"] => "text"
["slider4"] => 1
["toggle4"] => 0
["text4"] => "text"
As you can see the Array is a little bit 'strange' in the sense that there isn't an logic identifier like (1 -> 2 -> 3). Instead there is the name of the input field (from Sencha) with the number added to this string.
The number you see on the end of the key (3, 8, 11, 4) are the actual ID's of the 'data'.
This is where I get stuck. For the further processing of the data I want to mend the received array to another array like such:
[0]
["questionid"] => 3 (<- Number on the end of the original key)
["toggle"] => value from toggle3
["slider"] => value from slider3
["text"] => value form text3
[1]
["questionid"] => 8 (<- Number on the end of the original key)
["toggle"] => value from toggle8
["slider"] => value from slider8
["text"] => value from text8
etc.
Or in other words, I want to group the data with the same ID at the end of the KEY together in a new Array.
Anyone got an idea on how to tackle this one?
Upvotes: 0
Views: 481
Reputation: 54649
Try:
<?php
$data = array(
"slider3" => 1,
"toggle3" => 0,
"text3" => "text",
"slider8" => 5,
"toggle8" => 0,
"text8" => "text",
"slider11" => 4,
"toggle11" => 0,
"text11" => "text",
"slider4" => 1,
"toggle4" => 0,
"text4" => "text",
);
$newData = array();
foreach ($data as $entryKey => $entry) {
if (preg_match('/^(.+?)(\d+)$/', $entryKey, $matches)) {
list(, $key, $id) = $matches;
if (!isset($newData[$id])) {
$newData[$id] = array(
'questionid' => $id
);
}
$newData[$id][$key] = $entry;
}
}
$newData = array_values($newData);
print_r($newData);
Output:
Array
(
[0] => Array
(
[questionid] => 3
[slider] => 1
[toggle] => 0
[text] => text
)
[1] => Array
(
[questionid] => 8
[slider] => 5
[toggle] => 0
[text] => text
)
[2] => Array
(
[questionid] => 11
[slider] => 4
[toggle] => 0
[text] => text
)
[3] => Array
(
[questionid] => 4
[slider] => 1
[toggle] => 0
[text] => text
)
)
Upvotes: 3